{% extends 'base.html' %}
{% load static %}

{% block title %}{{ worldcup.name }} - 世界杯详情 - Creeps Judge{% endblock %}

{% block extra_css %}
<link href="{% static 'css/worldcup.css' %}" rel="stylesheet">
<style>
    .container {
        background: transparent;
        backdrop-filter: none;
        border-radius: 0;
        padding: 0;
        margin-top: 20px;
        margin-bottom: 20px;
        box-shadow: none;
        border: none;
        color: rgba(255, 255, 255, 0.9);
    }

    .worldcup-header {
        background: linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(30, 30, 60, 0.9) 100%);
        backdrop-filter: blur(15px);
        border-radius: 20px;
        border: 2px solid rgba(255, 215, 0, 0.5);
        padding: 20px;
        margin-bottom: 5px;
        text-align: center;
        box-shadow:
            0 8px 32px rgba(0, 0, 0, 0.3),
            0 0 20px rgba(255, 215, 0, 0.2),
            inset 0 0 15px rgba(255, 255, 255, 0.05);
    }

    .worldcup-title {
        font-size: 2.5rem;
        font-weight: 800;
        color: #FFD700;
        margin: 0 0 10px;
        text-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
    }

    .worldcup-status {
        display: inline-block;
        padding: 8px 20px;
        border-radius: 15px;
        font-size: 1rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 1px;
        margin-bottom: 15px;
    }

    .status-preparing {
        background: linear-gradient(135deg, #FFA500, #FF8C00);
        color: white;
        box-shadow: 0 4px 12px rgba(255, 165, 0, 0.4);
    }

    .status-ready {
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
        box-shadow: 0 4px 12px rgba(40, 167, 69, 0.4);
    }

    .status-regular_season {
        background: linear-gradient(135deg, #32CD32, #228B22);
        color: white;
        box-shadow: 0 4px 12px rgba(50, 205, 50, 0.4);
    }

    .status-regular_finished {
        background: linear-gradient(135deg, #4169E1, #1E90FF);
        color: white;
        box-shadow: 0 4px 12px rgba(65, 105, 225, 0.4);
    }

    .status-championship_ready {
        background: linear-gradient(135deg, #FFD700, #FFA500);
        color: #212529;
        box-shadow: 0 4px 12px rgba(255, 215, 0, 0.4);
        animation: pulse 2s infinite;
    }

    .status-championship {
        background: linear-gradient(135deg, #FF6347, #DC143C);
        color: white;
        box-shadow: 0 4px 12px rgba(255, 99, 71, 0.4);
        position: relative;
    }

    /* 冠军赛阶段进度显示样式 */
    .status-championship .championship-stage-progress {
        font-size: 0.9em;
        opacity: 0.9;
        margin-left: 8px;
        font-weight: 500;
    }

    .status-championship .championship-waiting {
        animation: waiting-pulse 2s infinite;
    }

    @keyframes waiting-pulse {
        0%, 100% {
            opacity: 1;
        }
        50% {
            opacity: 0.7;
        }
    }

    @keyframes pulse {
        0%, 100% {
            transform: scale(1);
            box-shadow: 0 4px 12px rgba(255, 215, 0, 0.4);
        }
        50% {
            transform: scale(1.05);
            box-shadow: 0 6px 20px rgba(255, 215, 0, 0.6);
        }
    }

    .status-finished {
        background: linear-gradient(135deg, #9370DB, #8A2BE2);
        color: white;
        box-shadow: 0 4px 12px rgba(147, 112, 219, 0.4);
    }

    .worldcup-description {
        font-size: 1.1rem;
        color: rgba(255, 255, 255, 0.8);
        line-height: 1.6;
        margin: 0;
    }

    .info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }

    .info-card {
        background: linear-gradient(135deg, rgba(0, 0, 0, 0.6) 0%, rgba(30, 30, 60, 0.8) 100%);
        backdrop-filter: blur(10px);
        border-radius: 15px;
        border: 1px solid rgba(255, 215, 0, 0.3);
        padding: 25px;
        text-align: center;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
    }

    .info-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
    }

    .info-icon {
        font-size: 2.5rem;
        margin-bottom: 15px;
        display: block;
    }

    .info-label {
        font-size: 0.9rem;
        color: rgba(255, 255, 255, 0.7);
        margin-bottom: 8px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .info-value {
        font-size: 1.8rem;
        font-weight: 700;
        color: #FFD700;
        margin: 0;
    }

    .section-card {
        background: linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(30, 30, 60, 0.9) 100%);
        backdrop-filter: blur(15px);
        border-radius: 20px;
        border: 2px solid rgba(255, 215, 0, 0.3);
        margin-bottom: 30px;
        overflow: hidden;
        box-shadow:
            0 8px 32px rgba(0, 0, 0, 0.3),
            0 0 20px rgba(255, 215, 0, 0.1),
            inset 0 0 15px rgba(255, 255, 255, 0.05);
    }

    .section-header {
        background: rgba(255, 215, 0, 0.1);
        padding: 20px 30px;
        border-bottom: 1px solid rgba(255, 215, 0, 0.3);
    }

    .section-title {
        font-size: 1.5rem;
        font-weight: 700;
        color: #FFD700;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .section-body {
        padding: 30px;
    }

    .participants-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 15px;
    }

    .participant-card {
        background: rgba(255, 255, 255, 0.05);
        border: 1px solid rgba(255, 215, 0, 0.2);
        border-radius: 10px;
        padding: 15px;
        text-align: center;
        transition: all 0.3s ease;
        position: relative;
    }

    .participant-card:hover {
        background: rgba(255, 215, 0, 0.1);
        border-color: rgba(255, 215, 0, 0.4);
        transform: translateY(-2px);
    }

    .participant-name {
        font-weight: 600;
        color: #FFD700;
        margin-bottom: 5px;
    }

    .participant-code {
        color: rgba(255, 255, 255, 0.7);
        font-size: 0.85rem;
        margin-bottom: 8px;
        font-style: italic;
    }

    .participant-score {
        color: rgba(255, 255, 255, 0.8);
        font-size: 0.9rem;
    }

    .participant-delete-btn {
        position: absolute;
        top: 5px;
        right: 5px;
        width: 24px;
        height: 24px;
        border: none;
        border-radius: 50%;
        background: rgba(220, 53, 69, 0.8);
        color: white;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        z-index: 10;
    }

    .participant-delete-btn:hover {
        background: rgba(220, 53, 69, 1);
        transform: scale(1.1);
        box-shadow: 0 2px 8px rgba(220, 53, 69, 0.4);
    }

    .action-buttons {
        background: linear-gradient(135deg, rgba(0, 0, 0, 0.6) 0%, rgba(30, 30, 60, 0.8) 100%);
        backdrop-filter: blur(10px);
        border-radius: 15px;
        border: 1px solid rgba(255, 215, 0, 0.3);
        padding: 20px;
        margin: 20px 0;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
    }

    .buttons-container {
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-items: center;
    }

    .admin-controls {
        display: contents;
    }

    .btn-action {
        padding: 12px 25px;
        border: none;
        border-radius: 10px;
        font-weight: 600;
        text-decoration: none;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        gap: 10px;
        font-size: 1rem;
        cursor: pointer;
    }

    .btn-primary {
        background: linear-gradient(135deg, #007bff, #0056b3);
        color: white;
        box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
    }

    .btn-primary:hover {
        background: linear-gradient(135deg, #0056b3, #004085);
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4);
        color: white;
        text-decoration: none;
    }

    .btn-success {
        background: linear-gradient(135deg, #28a745, #1e7e34);
        color: white;
        box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
    }

    .btn-success:hover {
        background: linear-gradient(135deg, #1e7e34, #155724);
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(40, 167, 69, 0.4);
        color: white;
        text-decoration: none;
    }

    .btn-warning {
        background: linear-gradient(135deg, #ffc107, #e0a800);
        color: #212529;
        box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3);
    }

    .btn-warning:hover {
        background: linear-gradient(135deg, #e0a800, #d39e00);
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(255, 193, 7, 0.4);
        color: #212529;
        text-decoration: none;
    }

    .btn-secondary {
        background: linear-gradient(135deg, #6c757d, #545b62);
        color: white;
        box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
    }

    .btn-secondary:hover {
        background: linear-gradient(135deg, #545b62, #495057);
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4);
        color: white;
        text-decoration: none;
    }

    .btn-info {
        background: linear-gradient(135deg, #17a2b8, #138496);
        color: white;
        box-shadow: 0 4px 15px rgba(23, 162, 184, 0.3);
    }

    .btn-info:hover {
        background: linear-gradient(135deg, #138496, #117a8b);
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(23, 162, 184, 0.4);
        color: white;
        text-decoration: none;
    }

    .btn-special {
        background: linear-gradient(135deg, #9c27b0, #7b1fa2);
        color: white;
        box-shadow: 0 4px 15px rgba(156, 39, 176, 0.3);
        position: relative;
        overflow: hidden;
    }

    .btn-special:hover {
        background: linear-gradient(135deg, #7b1fa2, #6a1b9a);
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(156, 39, 176, 0.4);
        color: white;
        text-decoration: none;
    }

    .btn-special::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: left 0.5s;
    }

    .btn-special:hover::before {
        left: 100%;
    }

    /* 队列控制按钮样式 */
    #queue-control-btn {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        border-radius: 6px;
        border: none;
        font-weight: 500;
        transition: all 0.3s ease;
        text-decoration: none;
        cursor: pointer;
    }

    #queue-control-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        text-decoration: none;
    }

    #queue-control-btn.btn-success {
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
    }

    #queue-control-btn.btn-success:hover {
        background: linear-gradient(135deg, #20c997, #17a2b8);
        color: white;
    }

    #queue-control-btn.btn-danger {
        background: linear-gradient(135deg, #dc3545, #c82333);
        color: white;
    }

    #queue-control-btn.btn-danger:hover {
        background: linear-gradient(135deg, #c82333, #bd2130);
        color: white;
    }

    #queue-control-icon {
        font-size: 1.1em;
    }

    /* 战斗队列状态按钮样式 */
    #battle-queue-status-btn.queue-idle {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        color: white;
        border: 2px solid rgba(40, 167, 69, 0.3);
    }

    #battle-queue-status-btn.queue-idle:hover {
        background: linear-gradient(135deg, #20c997 0%, #17a2b8 100%);
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(40, 167, 69, 0.4);
    }

    #battle-queue-status-btn.queue-busy {
        background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
        color: #212529;
        border: 2px solid rgba(255, 193, 7, 0.3);
    }

    #battle-queue-status-btn.queue-busy:hover {
        background: linear-gradient(135deg, #fd7e14 0%, #dc3545 100%);
        color: white;
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(255, 193, 7, 0.4);
    }

    #battle-queue-status-btn.queue-overloaded {
        background: linear-gradient(135deg, #dc3545 0%, #6f42c1 100%);
        color: white;
        border: 2px solid rgba(220, 53, 69, 0.3);
    }

    #battle-queue-status-btn.queue-overloaded:hover {
        background: linear-gradient(135deg, #6f42c1 0%, #495057 100%);
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(220, 53, 69, 0.4);
    }

    #battle-queue-status-btn.queue-error {
        background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
        color: white;
        border: 2px solid rgba(108, 117, 125, 0.3);
    }

    #battle-queue-status-btn.queue-error:hover {
        background: linear-gradient(135deg, #495057 0%, #343a40 100%);
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(108, 117, 125, 0.4);
    }

    .empty-state {
        text-align: center;
        padding: 40px 20px;
        color: rgba(255, 255, 255, 0.6);
    }

    .empty-icon {
        font-size: 3rem;
        margin-bottom: 15px;
        opacity: 0.5;
    }

    .timeline {
        position: relative;
        padding-left: 30px;
    }

    .timeline::before {
        content: '';
        position: absolute;
        left: 15px;
        top: 0;
        bottom: 0;
        width: 2px;
        background: linear-gradient(to bottom, #FFD700, rgba(255, 215, 0, 0.3));
    }

    .timeline-item {
        position: relative;
        margin-bottom: 25px;
        padding-left: 25px;
    }

    .timeline-item::before {
        content: '';
        position: absolute;
        left: -8px;
        top: 5px;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background: #FFD700;
        border: 3px solid rgba(0, 0, 0, 0.8);
    }

    .timeline-content {
        background: rgba(255, 255, 255, 0.05);
        border-radius: 10px;
        padding: 15px;
        border-left: 3px solid #FFD700;
    }

    .timeline-title {
        font-weight: 600;
        color: #FFD700;
        margin-bottom: 5px;
    }

    .timeline-time {
        font-size: 0.85rem;
        color: rgba(255, 255, 255, 0.6);
    }

    .breadcrumb {
        background: rgba(255, 255, 255, 0.05);
        border-radius: 10px;
        padding: 15px 20px;
        margin-bottom: 20px;
        border: 1px solid rgba(255, 215, 0, 0.2);
    }

    .breadcrumb-item {
        color: rgba(255, 255, 255, 0.7);
    }

    .breadcrumb-item.active {
        color: #FFD700;
    }

    .breadcrumb-item + .breadcrumb-item::before {
        content: '>';
        color: rgba(255, 255, 255, 0.5);
        margin: 0 8px;
    }

    .breadcrumb a {
        color: rgba(255, 255, 255, 0.8);
        text-decoration: none;
        transition: color 0.3s ease;
    }

    .breadcrumb a:hover {
        color: #FFD700;
        text-decoration: none;
    }

    /* 模态框样式 */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        backdrop-filter: blur(5px);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: 10000;
        animation: fadeIn 0.3s ease;
    }

    .modal-overlay.show {
        display: flex;
    }

    .progress-modal {
        background: linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(30, 30, 60, 0.95) 100%);
        backdrop-filter: blur(20px);
        border-radius: 20px;
        border: 2px solid rgba(255, 215, 0, 0.5);
        padding: 30px;
        max-width: 500px;
        width: 90%;
        box-shadow:
            0 20px 60px rgba(0, 0, 0, 0.5),
            0 0 30px rgba(255, 215, 0, 0.3),
            inset 0 0 20px rgba(255, 255, 255, 0.05);
        animation: modalSlideIn 0.4s ease;
        position: relative;
    }

    .modal-header {
        text-align: center;
        margin-bottom: 25px;
        padding-bottom: 15px;
        border-bottom: 1px solid rgba(255, 215, 0, 0.3);
    }

    .modal-title {
        font-size: 1.5rem;
        font-weight: 700;
        color: #FFD700;
        margin: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
    }

    .modal-icon {
        font-size: 1.8rem;
    }

    .modal-body {
        margin-bottom: 25px;
    }

    .progress-info {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
        margin-bottom: 20px;
    }

    .progress-stat {
        text-align: center;
        padding: 15px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 10px;
        border: 1px solid rgba(255, 215, 0, 0.2);
    }

    .progress-stat-label {
        font-size: 0.9rem;
        color: rgba(255, 255, 255, 0.7);
        margin-bottom: 5px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .progress-stat-value {
        font-size: 1.5rem;
        font-weight: 700;
        color: #FFD700;
        margin: 0;
    }

    .progress-bar-container {
        margin: 20px 0;
    }

    .progress-bar-label {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        color: rgba(255, 255, 255, 0.9);
        font-weight: 600;
    }

    .progress-percentage {
        color: #FFD700;
        font-size: 1.1rem;
        font-weight: 700;
    }

    .progress-bar {
        width: 100%;
        height: 12px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 6px;
        overflow: hidden;
        position: relative;
        box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.3);
    }

    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #FFD700, #FFA500, #FFD700);
        background-size: 200% 100%;
        border-radius: 6px;
        transition: width 0.8s ease;
        animation: progressShine 2s infinite;
        position: relative;
    }

    .progress-fill::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
        animation: progressGlow 1.5s infinite;
    }

    .championship-notice {
        background: linear-gradient(135deg, rgba(255, 99, 71, 0.2), rgba(220, 20, 60, 0.2));
        border: 1px solid rgba(255, 99, 71, 0.5);
        border-radius: 10px;
        padding: 15px;
        margin-top: 15px;
        text-align: center;
    }

    .championship-notice-icon {
        font-size: 1.5rem;
        color: #FF6347;
        margin-bottom: 8px;
    }

    .championship-notice-text {
        color: rgba(255, 255, 255, 0.9);
        font-weight: 600;
        margin: 0;
    }

    /* 战斗状态详情样式 */
    .battle-status-breakdown {
        margin: 20px 0;
        padding: 20px;
        background: rgba(255, 255, 255, 0.03);
        border-radius: 12px;
        border: 1px solid rgba(255, 215, 0, 0.2);
    }

    .breakdown-title {
        color: #FFD700;
        font-size: 1.1rem;
        font-weight: 600;
        margin: 0 0 15px 0;
        text-align: center;
    }

    .status-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 15px;
    }

    .status-item {
        display: flex;
        align-items: center;
        padding: 12px;
        border-radius: 10px;
        transition: all 0.3s ease;
        border: 1px solid transparent;
    }

    .status-item.running {
        background: rgba(40, 167, 69, 0.1);
        border-color: rgba(40, 167, 69, 0.3);
    }

    .status-item.pending {
        background: rgba(255, 193, 7, 0.1);
        border-color: rgba(255, 193, 7, 0.3);
    }

    .status-item.error {
        background: rgba(220, 53, 69, 0.1);
        border-color: rgba(220, 53, 69, 0.3);
    }

    .status-icon {
        font-size: 1.2rem;
        margin-right: 10px;
        min-width: 24px;
        text-align: center;
    }

    .status-info {
        flex: 1;
    }

    .status-label {
        font-size: 0.85rem;
        color: rgba(255, 255, 255, 0.7);
        margin-bottom: 2px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .status-value {
        font-size: 1.2rem;
        font-weight: 700;
        color: white;
    }

    .status-item.running .status-value {
        color: #28a745;
    }

    .status-item.pending .status-value {
        color: #ffc107;
    }

    .status-item.error .status-value {
        color: #dc3545;
    }

    .modal-footer {
        text-align: center;
    }

    .modal-close-btn {
        background: linear-gradient(135deg, #6c757d, #545b62);
        color: white;
        border: none;
        padding: 12px 30px;
        border-radius: 10px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
    }

    .modal-close-btn:hover {
        background: linear-gradient(135deg, #545b62, #495057);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4);
    }

    .search-section {
        margin-bottom: 20px;
    }

    .search-input {
        width: 100%;
        padding: 12px 15px;
        border: 1px solid rgba(255, 215, 0, 0.3);
        border-radius: 10px;
        background: rgba(255, 255, 255, 0.05);
        color: white;
        font-size: 1rem;
        transition: all 0.3s ease;
    }

    .search-input:focus {
        outline: none;
        border-color: #FFD700;
        box-shadow: 0 0 10px rgba(255, 215, 0, 0.3);
    }

    .search-input::placeholder {
        color: rgba(255, 255, 255, 0.5);
    }

    .participants-section, .selected-section {
        margin-bottom: 20px;
    }

    .participants-section h4, .selected-section h4 {
        color: #FFD700;
        margin-bottom: 15px;
        font-size: 1.1rem;
        font-weight: 600;
    }

    .users-list, .selected-list {
        max-height: 200px;
        overflow-y: auto;
        border: 1px solid rgba(255, 215, 0, 0.2);
        border-radius: 10px;
        background: rgba(255, 255, 255, 0.02);
    }

    .user-item {
        padding: 15px;
        border-bottom: 1px solid rgba(255, 215, 0, 0.1);
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: all 0.3s ease;
        cursor: pointer;
    }

    .user-item:hover {
        background: rgba(255, 215, 0, 0.1);
    }

    .user-item:last-child {
        border-bottom: none;
    }

    .user-info {
        flex: 1;
    }

    .user-name {
        color: white;
        font-weight: 600;
        margin-bottom: 5px;
    }

    .user-codes {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .code-option {
        padding: 4px 8px;
        background: rgba(255, 215, 0, 0.2);
        border: 1px solid rgba(255, 215, 0, 0.3);
        border-radius: 5px;
        font-size: 0.8rem;
        color: #FFD700;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .code-option:hover {
        background: rgba(255, 215, 0, 0.3);
    }

    .code-option.selected {
        background: #FFD700;
        color: #000;
    }

    .user-actions {
        display: flex;
        gap: 10px;
        align-items: center;
    }

    .btn-select {
        padding: 6px 12px;
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
        border: none;
        border-radius: 5px;
        font-size: 0.8rem;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-select:hover {
        background: linear-gradient(135deg, #20c997, #17a2b8);
        transform: translateY(-1px);
    }

    .btn-remove {
        padding: 6px 12px;
        background: linear-gradient(135deg, #dc3545, #c82333);
        color: white;
        border: none;
        border-radius: 5px;
        font-size: 0.8rem;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-remove:hover {
        background: linear-gradient(135deg, #c82333, #bd2130);
        transform: translateY(-1px);
    }

    .selected-participant {
        padding: 10px 15px;
        background: rgba(40, 167, 69, 0.2);
        border: 1px solid rgba(40, 167, 69, 0.3);
        border-radius: 8px;
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .selected-info {
        color: white;
    }

    .selected-name {
        font-weight: 600;
        margin-bottom: 3px;
    }

    .selected-code {
        font-size: 0.9rem;
        color: rgba(255, 255, 255, 0.8);
    }

    .error-modal {
        background: linear-gradient(135deg, rgba(139, 0, 0, 0.9) 0%, rgba(220, 20, 60, 0.95) 100%);
        backdrop-filter: blur(20px);
        border-radius: 20px;
        border: 2px solid rgba(255, 69, 0, 0.5);
        padding: 30px;
        max-width: 450px;
        width: 90%;
        box-shadow:
            0 20px 60px rgba(0, 0, 0, 0.5),
            0 0 30px rgba(255, 69, 0, 0.3),
            inset 0 0 20px rgba(255, 255, 255, 0.05);
        animation: modalSlideIn 0.4s ease;
        text-align: center;
    }

    .error-icon {
        font-size: 3rem;
        color: #FF4500;
        margin-bottom: 15px;
    }

    .error-title {
        font-size: 1.3rem;
        font-weight: 700;
        color: #FFB6C1;
        margin-bottom: 15px;
    }

    .error-message {
        color: rgba(255, 255, 255, 0.9);
        line-height: 1.5;
        margin-bottom: 20px;
    }

    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }

    @keyframes modalSlideIn {
        from {
            opacity: 0;
            transform: translateY(-50px) scale(0.9);
        }
        to {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
    }

    @keyframes progressShine {
        0% { background-position: 200% 0; }
        100% { background-position: -200% 0; }
    }

    @keyframes progressGlow {
        0% { transform: translateX(-100%); }
        100% { transform: translateX(100%); }
    }

    @keyframes slideInRight {
        from {
            opacity: 0;
            transform: translateX(100%);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }

    @keyframes slideOutRight {
        from {
            opacity: 1;
            transform: translateX(0);
        }
        to {
            opacity: 0;
            transform: translateX(100%);
        }
    }

    /* 用户选择卡片样式 */
    .user-card {
        background: rgba(30, 30, 60, 0.9) !important;
        color: rgba(200, 220, 255, 0.9) !important;
        border: 1px solid rgba(100, 150, 255, 0.3) !important;
        transition: all 0.3s ease;
        cursor: pointer;
    }

    .user-card:hover {
        background: rgba(40, 40, 80, 0.95) !important;
        color: rgba(230, 240, 255, 0.95) !important;
        transform: translateY(-3px);
        box-shadow: 0 8px 20px rgba(100, 150, 255, 0.2);
    }

    .user-card.selected {
        background: linear-gradient(135deg, rgba(100, 150, 255, 0.3) 0%, rgba(0, 212, 255, 0.4) 100%) !important;
        border-color: rgba(100, 150, 255, 0.8) !important;
        box-shadow: 0 8px 20px rgba(100, 150, 255, 0.3) !important;
    }

    /* 代码选择卡片样式 */
    .code-card {
        background: rgba(30, 30, 60, 0.9) !important;
        color: rgba(200, 220, 255, 0.9) !important;
        border: 1px solid rgba(100, 150, 255, 0.3) !important;
        transition: all 0.3s ease;
        cursor: pointer;
    }

    .code-card:hover {
        background: rgba(40, 40, 80, 0.95) !important;
        color: rgba(230, 240, 255, 0.95) !important;
        transform: translateY(-3px);
        box-shadow: 0 8px 20px rgba(100, 150, 255, 0.2);
    }

    /* Python 语言卡片 */
    .code-card-python {
        background: linear-gradient(135deg, rgba(53, 114, 165, 0.3) 0%, rgba(32, 74, 135, 0.4) 100%) !important;
        border-color: rgba(53, 114, 165, 0.5) !important;
    }

    .code-card-python:hover {
        background: linear-gradient(135deg, rgba(53, 114, 165, 0.4) 0%, rgba(32, 74, 135, 0.5) 100%) !important;
        border-color: rgba(53, 114, 165, 0.8) !important;
        box-shadow: 0 8px 20px rgba(53, 114, 165, 0.3) !important;
    }

    /* JavaScript 语言卡片 */
    .code-card-javascript {
        background: linear-gradient(135deg, rgba(240, 219, 79, 0.3) 0%, rgba(227, 183, 31, 0.4) 100%) !important;
        border-color: rgba(240, 219, 79, 0.5) !important;
    }

    .code-card-javascript:hover {
        background: linear-gradient(135deg, rgba(240, 219, 79, 0.4) 0%, rgba(227, 183, 31, 0.5) 100%) !important;
        border-color: rgba(240, 219, 79, 0.8) !important;
        box-shadow: 0 8px 20px rgba(240, 219, 79, 0.3) !important;
    }

    /* TypeScript 语言卡片 */
    .code-card-typescript {
        background: linear-gradient(135deg, rgba(255, 105, 180, 0.3) 0%, rgba(219, 112, 147, 0.4) 100%) !important;
        border-color: rgba(255, 105, 180, 0.5) !important;
    }

    .code-card-typescript:hover {
        background: linear-gradient(135deg, rgba(255, 105, 180, 0.4) 0%, rgba(219, 112, 147, 0.5) 100%) !important;
        border-color: rgba(255, 105, 180, 0.8) !important;
        box-shadow: 0 8px 20px rgba(255, 105, 180, 0.3) !important;
    }

    /* Lua 语言卡片 */
    .code-card-lua {
        background: linear-gradient(135deg, rgba(46, 139, 87, 0.3) 0%, rgba(60, 179, 113, 0.4) 100%) !important;
        border-color: rgba(46, 139, 87, 0.5) !important;
    }

    .code-card-lua:hover {
        background: linear-gradient(135deg, rgba(46, 139, 87, 0.4) 0%, rgba(60, 179, 113, 0.5) 100%) !important;
        border-color: rgba(46, 139, 87, 0.8) !important;
        box-shadow: 0 8px 20px rgba(46, 139, 87, 0.3) !important;
    }

    /* 语言标签样式 */
    .language-badge-python {
        background: linear-gradient(135deg, rgba(53, 114, 165, 0.8), rgba(32, 74, 135, 0.8)) !important;
        color: white !important;
        border: 1px solid rgba(53, 114, 165, 0.6) !important;
    }

    .language-badge-javascript {
        background: linear-gradient(135deg, rgba(240, 219, 79, 0.8), rgba(227, 183, 31, 0.8)) !important;
        color: rgba(0, 0, 0, 0.8) !important;
        border: 1px solid rgba(240, 219, 79, 0.6) !important;
    }

    .language-badge-typescript {
        background: linear-gradient(135deg, rgba(255, 105, 180, 0.8), rgba(219, 112, 147, 0.8)) !important;
        color: white !important;
        border: 1px solid rgba(255, 105, 180, 0.6) !important;
    }

    .language-badge-lua {
        background: linear-gradient(135deg, rgba(46, 139, 87, 0.8), rgba(60, 179, 113, 0.8)) !important;
        color: white !important;
        border: 1px solid rgba(46, 139, 87, 0.6) !important;
    }

    /* 星标代码样式 */
    .starred-code {
        position: relative;
        border: 2px solid rgba(255, 193, 7, 0.6) !important;
        box-shadow: 0 4px 15px rgba(255, 193, 7, 0.2) !important;
    }

    .starred-code:hover {
        border-color: rgba(255, 193, 7, 0.8) !important;
        box-shadow: 0 8px 25px rgba(255, 193, 7, 0.3) !important;
    }

    .star-indicator {
        position: absolute;
        top: -8px;
        right: -8px;
        background: linear-gradient(135deg, #ffc107, #ff8f00);
        color: white;
        border-radius: 50%;
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        z-index: 10;
        box-shadow: 0 2px 8px rgba(255, 193, 7, 0.4);
        border: 2px solid rgba(255, 255, 255, 0.9);
    }

    .star-indicator i {
        animation: starPulse 2s infinite;
    }

    @keyframes starPulse {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.1); }
    }

    /* 用户代码选择区域样式 */
    .user-code-selection {
        background: rgba(255, 255, 255, 0.05);
        border: 1px solid rgba(100, 150, 255, 0.2);
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 20px;
    }

    .user-code-selection h5 {
        color: rgba(255, 255, 255, 0.9);
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .user-code-selection h5 i {
        color: #6496ff;
    }

    .btn-gradient {
        background: linear-gradient(135deg, #6496ff, #00d4ff);
        border: none;
        color: white;
        padding: 12px 30px;
        border-radius: 25px;
        font-weight: 600;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(100, 150, 255, 0.3);
        cursor: pointer;
    }

    .btn-gradient:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(100, 150, 255, 0.4);
        color: white;
        text-decoration: none;
    }



    /* 冠军赛队列状态按钮特殊样式 */
    #championship-queue-status-btn {
        border: 2px solid rgba(255, 99, 71, 0.3);
        background: linear-gradient(135deg, rgba(255, 99, 71, 0.1), rgba(220, 20, 60, 0.1));
        transition: all 0.3s ease;
    }

    #championship-queue-status-btn.queue-idle {
        background: linear-gradient(135deg, rgba(108, 117, 125, 0.2), rgba(73, 80, 87, 0.2));
        color: #6c757d;
        border-color: rgba(108, 117, 125, 0.3);
    }

    #championship-queue-status-btn.queue-busy {
        background: linear-gradient(135deg, rgba(255, 193, 7, 0.2), rgba(255, 140, 0, 0.2));
        color: #ffc107;
        border-color: rgba(255, 193, 7, 0.4);
        animation: championship-pulse 2s infinite;
    }

    #championship-queue-status-btn.queue-overloaded {
        background: linear-gradient(135deg, rgba(220, 53, 69, 0.2), rgba(255, 99, 71, 0.2));
        color: #dc3545;
        border-color: rgba(220, 53, 69, 0.4);
        animation: championship-pulse-fast 1s infinite;
    }

    #championship-queue-status-btn.queue-error {
        background: linear-gradient(135deg, rgba(108, 117, 125, 0.2), rgba(73, 80, 87, 0.2));
        color: #6c757d;
        border-color: rgba(108, 117, 125, 0.3);
    }

    @keyframes championship-pulse {
        0%, 100% {
            box-shadow: 0 4px 15px rgba(255, 99, 71, 0.3);
            transform: scale(1);
        }
        50% {
            box-shadow: 0 6px 25px rgba(255, 99, 71, 0.5);
            transform: scale(1.02);
        }
    }

    @keyframes championship-pulse-fast {
        0%, 100% {
            box-shadow: 0 4px 15px rgba(220, 53, 69, 0.4);
            transform: scale(1);
        }
        50% {
            box-shadow: 0 8px 30px rgba(220, 53, 69, 0.6);
            transform: scale(1.03);
        }
    }



    /* 全选复选框样式 */
    .select-all-container {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .select-all-container .form-check {
        margin-bottom: 0;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .select-all-container .form-check-input {
        width: 18px;
        height: 18px;
        border: 2px solid rgba(255, 215, 0, 0.6);
        background-color: rgba(0, 0, 0, 0.3);
        border-radius: 4px;
        transition: all 0.3s ease;
    }

    .select-all-container .form-check-input:checked {
        background-color: #FFD700;
        border-color: #FFD700;
        box-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
    }

    .select-all-container .form-check-input:indeterminate {
        background-color: rgba(255, 215, 0, 0.5);
        border-color: #FFD700;
        box-shadow: 0 0 8px rgba(255, 215, 0, 0.3);
    }

    .select-all-container .form-check-label {
        color: rgba(255, 255, 255, 0.9);
        font-size: 0.9rem;
        font-weight: 500;
        cursor: pointer;
        margin-bottom: 0;
        transition: color 0.3s ease;
    }

    .select-all-container .form-check-label:hover {
        color: #FFD700;
    }

    #select-all-text {
        transition: color 0.3s ease;
    }

</style>
{% endblock %}

{% block content %}
<div class="container">
    <!-- 面包屑导航 -->
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{% url 'battles:worldcup_list' %}">世界杯列表</a></li>
            <li class="breadcrumb-item active" aria-current="page">{{ worldcup.name }}</li>
        </ol>
    </nav>

    <!-- 世界杯头部信息 -->
    <div class="worldcup-header">
        <h1 class="worldcup-title">🏆 {{ worldcup.name }}</h1>
        <div class="worldcup-status status-{{ worldcup.status }}">
            {% if worldcup.status == 'preparing' %}
                🔧 准备中...
            {% elif worldcup.status == 'ready' %}
                ✅ 参赛名单已确认, 准备就绪
            {% elif worldcup.status == 'regular_season' %}
                ⚔️ 常规赛进行中...
            {% elif worldcup.status == 'regular_finished' %}
                ✅ 常规赛已结束
            {% elif worldcup.status == 'championship_ready' %}
                ✅ 冠军赛16强已匹配, 准备就绪
            {% elif worldcup.status == 'championship' %}
                {% if championship_stages_info %}
                    {% comment %}优先显示正在进行的阶段{% endcomment %}
                    {% if championship_stages_info.round_16.status == 'in_progress' %}
                        🏆 {{ championship_stages_info.round_16.name }}进行中...<span class="championship-stage-progress">({{ championship_stages_info.round_16.completed_matches }}/{{ championship_stages_info.round_16.total_matches }})</span>
                    {% elif championship_stages_info.quarter_final.status == 'in_progress' %}
                        🏆 {{ championship_stages_info.quarter_final.name }}进行中...<span class="championship-stage-progress">({{ championship_stages_info.quarter_final.completed_matches }}/{{ championship_stages_info.quarter_final.total_matches }})</span>
                    {% elif championship_stages_info.semi_final.status == 'in_progress' %}
                        🏆 {{ championship_stages_info.semi_final.name }}进行中...<span class="championship-stage-progress">({{ championship_stages_info.semi_final.completed_matches }}/{{ championship_stages_info.semi_final.total_matches }})</span>
                    {% elif championship_stages_info.final.status == 'in_progress' %}
                        🏆 {{ championship_stages_info.final.name }}进行中...<span class="championship-stage-progress">({{ championship_stages_info.final.completed_matches }}/{{ championship_stages_info.final.total_matches }})</span>
                    {% comment %}然后显示等待开始的阶段{% endcomment %}
                    {% elif championship_stages_info.round_16.status == 'waiting' %}
                        <span class="championship-waiting">⏳ 等待{{ championship_stages_info.round_16.name }}开始...</span>
                    {% elif championship_stages_info.quarter_final.status == 'waiting' %}
                        <span class="championship-waiting">⏳ 等待{{ championship_stages_info.quarter_final.name }}开始...</span>
                    {% elif championship_stages_info.semi_final.status == 'waiting' %}
                        <span class="championship-waiting">⏳ 等待{{ championship_stages_info.semi_final.name }}开始...</span>
                    {% elif championship_stages_info.final.status == 'waiting' %}
                        <span class="championship-waiting">⏳ 等待{{ championship_stages_info.final.name }}开始...</span>
                    {% comment %}检查是否所有阶段都已完成{% endcomment %}
                    {% elif championship_stages_info.final.status == 'completed' %}
                        🏆 冠军赛即将结束...
                    {% comment %}如果16强还未开始{% endcomment %}
                    {% elif championship_stages_info.round_16.status == 'not_started' %}
                        🏆 冠军赛准备开始...
                    {% else %}
                        🏆 冠军赛进行中...
                    {% endif %}
                {% else %}
                    🏆 冠军赛进行中...
                {% endif %}
            {% elif worldcup.status == 'finished' %}
                ✅ 比赛已结束
            {% endif %}
        </div>



        {% if worldcup.description %}
        <p class="worldcup-description">{{ worldcup.description }}</p>
        {% endif %}
    </div>

    <!-- 基本信息 -->
    <div class="info-grid">
        {% if worldcup.started_at %}
        <div class="info-card">
            <span class="info-icon">🚀</span>
            <div class="info-label">开始时间</div>
            <div class="info-value">{{ worldcup.started_at|date:"m-d H:i" }}</div>
        </div>
        {% endif %}
        {% if worldcup.finished_at %}
        <div class="info-card">
            <span class="info-icon">🏁</span>
            <div class="info-label">结束时间</div>
            <div class="info-value">{{ worldcup.finished_at|date:"m-d H:i" }}</div>
        </div>
        {% endif %}
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
        <!-- 导航按钮行 -->
        <div class="buttons-container">
            <a href="{% url 'battles:worldcup_list' %}" class="btn-action btn-secondary">
                ← 返回列表
            </a>

            {% if worldcup.status == 'regular_season' or worldcup.status == 'regular_finished' or worldcup.status == 'championship_ready' or worldcup.status == 'championship' or worldcup.status == 'finished' %}
            <a href="{% url 'battles:worldcup_regular_season' worldcup.id %}" class="btn-action btn-success">
                🥇 常规赛排行榜
            </a>
            {% endif %}

            {% if worldcup.status == 'regular_season' or worldcup.status == 'regular_finished' or worldcup.status == 'championship_ready' or worldcup.status == 'championship' or worldcup.status == 'finished' %}
            <a href="{% url 'battles:worldcup_battles' worldcup.id %}" class="btn-action btn-info">
                ⚔️ 常规赛对战记录
            </a>
            {% endif %}

            {% if worldcup.status == 'championship_ready' or worldcup.status == 'championship' or worldcup.status == 'finished' %}
            <a href="{% url 'battles:worldcup_championship' worldcup.id %}" class="btn-action btn-warning">
                🏆 冠军赛对战图
            </a>
            {% endif %}

            <button onclick="refreshData()" class="btn-action btn-primary" style="margin-left: 10px;">
                <i class="fas fa-sync-alt"></i> 刷新数据
            </button>
        </div>

        <!-- Admin管理按钮 -->
        {% if user.is_staff %}
        <!-- 分隔线 -->
        <div style="border-top: 2px solid rgba(255, 215, 0, 0.3); margin: 15px 0;"></div>

        <!-- Admin管理按钮行 -->
        <div class="buttons-container">
            <div class="admin-controls">

                {% if worldcup.status == 'preparing' %}
                <!-- 比赛准备管理功能区域 -->
                <div style="border-top: 2px solid rgba(255, 215, 0, 0.3); margin-top: 15px; padding-top: 15px;">
                    <div style="text-align: center; margin-bottom: 10px;">
                        <span style="color: #FFD700; font-weight: 600; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 1px;">🛠️ 比赛准备管理</span>
                    </div>
                    <div class="buttons-container">
                        <button id="confirm-participants-btn" class="btn-action btn-primary" data-worldcup-id="{{ worldcup.id }}">
                            ✅ 确定参赛名单
                        </button>
                    </div>
                </div>
                {% endif %}

                {% if worldcup.status == 'ready' %}
                <!-- 比赛启动管理功能区域 -->
                <div style="margin-top: 15px;">
                    <div style="text-align: center; margin-bottom: 10px;">
                        <span style="color: #FFD700; font-weight: 600; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 1px;">🚀 比赛启动管理</span>
                    </div>
                    <div class="buttons-container">
                        <button id="start-regular-season-btn" class="btn-action btn-success" data-worldcup-id="{{ worldcup.id }}">
                            🚀 开始常规赛
                        </button>
                    </div>
                </div>
                {% endif %}

                {% if worldcup.status == 'regular_season' %}
                <!-- 常规赛管理功能区域 -->
                <div style="margin-top: 15px;">
                    <div style="text-align: center; margin-bottom: 10px;">
                        <span style="color: #FFD700; font-weight: 600; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 1px;">⚔️ 常规赛管理</span>
                    </div>
                    <!-- <button id="check-progress-btn" class="btn-action btn-info" data-worldcup-id="{{ worldcup.id }}">
                        ⏳ 检查比赛进度
                    </button> -->
                    <button id="battle-queue-status-btn" class="btn-action btn-info" data-worldcup-id="{{ worldcup.id }}">
                        <span id="queue-status-icon">📊</span>战斗队列状态
                    </button>
                    <button id="queue-control-btn" class="btn-action" data-worldcup-id="{{ worldcup.id }}" style="display: none;">
                        <span id="queue-control-icon">🔄</span>
                        <span id="queue-control-text">重启战斗队列</span>
                    </button>
                    <button id="requeue-error-pending-battles-btn" class="btn-action btn-warning" data-worldcup-id="{{ worldcup.id }}">
                        🚀 拉取错误等待进常规赛队列
                    </button>
                    <button id="force-end-regular-season-btn" class="btn-action btn-danger" data-worldcup-id="{{ worldcup.id }}">
                        ⚠️强制结束常规赛
                    </button>
                    <a href="{% url 'battles:worldcup_special_rankings' worldcup.id %}" class="btn-action btn-special">
                        🌟 特色排行榜
                    </a>
                </div>
                {% endif %}

                {% if worldcup.status == 'regular_finished' %}
                <!-- 常规赛完成管理功能区域 -->
                <div style="margin-top: 5px;">
                    <div style="text-align: center; margin-bottom: 10px;">
                        <span style="color: #FFD700; font-weight: 600; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 1px;">🎯 常规赛完成管理</span>
                    </div>
                    <div class="buttons-container">
                        <button id="start-round16-grouping-btn" class="btn-action btn-warning" data-worldcup-id="{{ worldcup.id }}">
                            🏆 16强分组准备
                        </button>
                        <a href="{% url 'battles:worldcup_special_rankings' worldcup.id %}" class="btn-action btn-special">
                            🌟 特色排行榜
                        </a>
                    </div>
                </div>
                {% endif %}

                {% if worldcup.status == 'championship_ready' %}
                <!-- 冠军赛准备管理功能区域 -->
                <div style="margin-top: 15px;">
                    <div style="text-align: center; margin-bottom: 10px;">
                        <span style="color: #FFD700; font-weight: 600; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 1px;">🏅 冠军赛准备管理</span>
                    </div>
                    <div class="buttons-container">
                        <button id="start-championship-battle-btn" class="btn-action btn-warning" data-worldcup-id="{{ worldcup.id }}">
                            ⚔️ 开始冠军赛战斗
                        </button>
                        <a href="{% url 'battles:worldcup_special_rankings' worldcup.id %}" class="btn-action btn-special">
                            🌟 特色排行榜
                        </a>
                    </div>
                </div>
                {% endif %}

                {% if worldcup.status == 'championship' %}
                <!-- 冠军赛管理功能区域 -->
                <div style="margin-top: 15px;">
                    <div style="text-align: center; margin-bottom: 10px;">
                        <span style="color: #FFD700; font-weight: 600; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 1px;">🏆 冠军赛管理</span>
                    </div>
                    <div class="buttons-container">
                        <!-- <button id="check-championship-progress-btn" class="btn-action btn-info" data-worldcup-id="{{ worldcup.id }}">
                            ⏳ 检查冠军赛进度
                        </button> -->
                        <button id="championship-queue-status-btn" class="btn-action btn-info" data-worldcup-id="{{ worldcup.id }}">
                            <span id="championship-queue-status-icon">📊</span>冠军赛队列状态
                        </button>
                        <button id="championship-queue-control-btn" class="btn-action" data-worldcup-id="{{ worldcup.id }}" style="display: none;">
                            <span id="championship-queue-control-icon">🔄</span>
                            <span id="championship-queue-control-text">重启冠军赛队列</span>
                        </button>
                        <button id="requeue-championship-pending-battles-btn" class="btn-action btn-warning" data-worldcup-id="{{ worldcup.id }}">
                            🚀 拉取错误等待进冠军队列
                        </button>
                        <button id="advance-next-stage-btn" class="btn-action btn-primary" data-worldcup-id="{{ worldcup.id }}">
                            ⏭️ 手动推进下一阶段
                        </button>
                        <button id="force-end-championship-btn" class="btn-action btn-danger" data-worldcup-id="{{ worldcup.id }}">
                            ⚠️强制结束冠军赛
                        </button>
                        <a href="{% url 'battles:worldcup_special_rankings' worldcup.id %}" class="btn-action btn-special">
                            🌟 特色排行榜
                        </a>
                    </div>
                </div>
                {% endif %}

                {% if worldcup.status == 'finished' %}
                <!-- 比赛完成管理功能区域 -->
                <div style="margin-top: 15px;">
                    <div style="text-align: center; margin-bottom: 10px;">
                        <span style="color: #FFD700; font-weight: 600; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 1px;">🎉 比赛完成管理</span>
                    </div>
                    <div class="buttons-container">
                        <a href="{% url 'battles:worldcup_special_rankings' worldcup.id %}" class="btn-action btn-special">
                            🌟 特色排行榜
                        </a>
                    </div>
                </div>
                {% endif %}

            </div>
        </div>
        {% endif %}
    </div>

    <!-- 战斗进度 -->
    {% if worldcup.status == 'regular_season' or worldcup.status == 'championship' %}
    <div class="section-card">
        <div class="section-header">
            <h2 class="section-title">
                <span>🚀</span>
                战斗进度
            </h2>
        </div>
        <div class="section-body">
            <div class="progress-info">
                <div class="progress-stat">
                    <div class="progress-stat-label">总对战数</div>
                    <div class="progress-stat-value" id="total-matches">0</div>
                </div>
                <div class="progress-stat">
                    <div class="progress-stat-label">已完成</div>
                    <div class="progress-stat-value" id="completed-matches">0</div>
                </div>
            </div>
            <div class="battle-status-breakdown">
                <h4 class="breakdown-title">战斗状态详情</h4>
                <div class="status-grid">
                    <div class="status-item running">
                        <div class="status-icon">🔄</div>
                        <div class="status-info">
                            <div class="status-label">进行中</div>
                            <div class="status-value" id="running-battles">0</div>
                        </div>
                    </div>
                    <div class="status-item pending">
                        <div class="status-icon">⏳</div>
                        <div class="status-info">
                            <div class="status-label">等待中</div>
                            <div class="status-value" id="pending-battles">0</div>
                        </div>
                    </div>
                    <div class="status-item error">
                        <div class="status-icon">❌</div>
                        <div class="status-info">
                            <div class="status-label">错误</div>
                            <div class="status-value" id="error-battles">0</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="progress-bar-container">
                <div class="progress-bar-label">
                    <span>完成进度</span>
                    <span class="progress-percentage" id="progress-percentage">0%</span>
                </div>
                <div class="progress-bar">
                    <div class="progress-fill" id="progress-fill" style="width: 0%"></div>
                </div>
            </div>
            <div id="championship-notice" class="championship-notice" style="display: none;">
                <div class="championship-notice-icon">🏆</div>
                <p class="championship-notice-text">常规赛已完成！现在可以开始冠军赛了。</p>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- 参赛选手 -->
    <div class="section-card">
        <div class="section-header">
            <h2 class="section-title">
                <span>👲</span>
                参赛选手 ({{ worldcup.participants.count }})
            </h2>
        </div>
        <div class="section-body">
            {% if worldcup.participants.exists %}
                <div class="participants-grid">
                    {% for participant in worldcup.participants.all %}
                    <div class="participant-card" data-participant-id="{{ participant.id }}">
                        {% if worldcup.status == 'preparing' and user.is_staff %}
                        <button class="participant-delete-btn"
                                data-participant-id="{{ participant.id }}"
                                data-participant-name="{{ participant.user.username }}"
                                title="移除参赛选手">
                            ×
                        </button>
                        {% endif %}
                        <div class="participant-name">{{ participant.user.username }}</div>
                        <div class="participant-code">代码: {{ participant.code.title }}</div>
                        {% if worldcup.status != 'preparing' %}
                        <div class="participant-score">
                            常规赛积分: {{ participant.total_score }}
                            {% if participant.championship_rank %}
                            <br>冠军赛排名: {{ participant.championship_rank }}
                            {% endif %}
                        </div>
                        {% endif %}
                    </div>
                    {% endfor %}
                </div>
            {% else %}
                <div class="empty-state">
                    <div class="empty-icon">👥</div>
                    <p>暂无参赛选手</p>
                </div>
            {% endif %}
        </div>
    </div>



    <!-- 选择参赛选手和代码 -->
    {% if worldcup.status == 'preparing' and user.is_staff %}
    <div class="section-card">
        <div class="section-header">
            <h2 class="section-title">
                <span>👥</span>
                选择参赛选手
            </h2>
        </div>
        <div class="section-body">
            <form id="participant-selection-form">
                {% csrf_token %}

                <!-- 用户选择 -->
                <div class="mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <label class="form-label mb-0">选择参赛用户:</label>
                        <div class="select-all-container">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="select-all-users" onchange="toggleSelectAll()">
                                <label class="form-check-label" for="select-all-users">
                                    <span id="select-all-text">全选</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="row" id="users-list">
                        <!-- 用户列表将通过JavaScript动态加载 -->
                        <div class="col-12 text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载可用用户...</p>
                        </div>
                    </div>
                </div>

                <!-- 代码选择 -->
                <div class="mb-4">
                    <label class="form-label">为每个用户选择代码:</label>
                    <div id="codes-selection" style="display: none;">
                        <!-- 代码选择将根据选中的用户动态显示 -->
                    </div>
                    <div id="no-users-selected" class="text-center text-muted">
                        <i class="fas fa-info-circle"></i>
                        请先选择参赛用户
                    </div>
                </div>

                <!-- 确定按钮 -->
                <div class="text-center">
                    <button type="button" id="confirm-selection-btn" class="btn-gradient" style="display: none;">
                        <i class="fas fa-check"></i> 确定选择
                    </button>
                </div>
            </form>
        </div>
    </div>
    {% endif %}

    <!-- 比赛进度 -->
    {% if worldcup.status != 'preparing' %}
    <div class="section-card">
        <div class="section-header">
            <h2 class="section-title">
                <span>⏳</span>
                比赛进度
            </h2>
        </div>
        <div class="section-body">
            <div class="timeline">
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">比赛创建</div>
                        <div class="timeline-time">{{ worldcup.created_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% if worldcup.status != 'preparing' %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">参赛名单确认</div>
                        <div class="timeline-time">准备就绪，共{{ worldcup.total_participants }}人参赛</div>
                    </div>
                </div>
                {% endif %}
                {% if worldcup.regular_season_started_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">常规赛开始</div>
                        <div class="timeline-time">{{ worldcup.regular_season_started_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}
                {% if worldcup.regular_season_finished_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">常规赛结束</div>
                        <div class="timeline-time">{{ worldcup.regular_season_finished_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}
                {% if worldcup.status == 'championship_ready' %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">冠军赛准备就绪</div>
                        <div class="timeline-time">前16名选手已确定，等待开始冠军赛</div>
                    </div>
                </div>
                {% endif %}
                {% if worldcup.championship_started_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">冠军赛开始</div>
                        <div class="timeline-time">{{ worldcup.championship_started_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}

                <!-- 16强阶段 -->
                {% if round_16_started_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">16强赛开始</div>
                        <div class="timeline-time">{{ round_16_started_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}
                {% if round_16_finished_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">16强赛结束</div>
                        <div class="timeline-time">{{ round_16_finished_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}

                <!-- 8强阶段 -->
                {% if quarter_final_started_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">8强赛开始</div>
                        <div class="timeline-time">{{ quarter_final_started_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}
                {% if quarter_final_finished_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">8强赛结束</div>
                        <div class="timeline-time">{{ quarter_final_finished_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}

                <!-- 4强阶段 -->
                {% if semi_final_started_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">4强赛开始</div>
                        <div class="timeline-time">{{ semi_final_started_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}
                {% if semi_final_finished_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">4强赛结束</div>
                        <div class="timeline-time">{{ semi_final_finished_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}

                <!-- 决赛阶段 -->
                {% if final_started_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">决赛开始</div>
                        <div class="timeline-time">{{ final_started_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}
                {% if final_finished_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">决赛结束</div>
                        <div class="timeline-time">{{ final_finished_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}

                {% if worldcup.finished_at %}
                <div class="timeline-item">
                    <div class="timeline-content">
                        <div class="timeline-title">比赛结束</div>
                        <div class="timeline-time">{{ worldcup.finished_at|date:"Y-m-d H:i:s" }}</div>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
    {% endif %}

</div>

<!-- 进度检查模态框 -->
<div id="progress-modal-overlay" class="modal-overlay">
    <div class="progress-modal">
        <div class="modal-header">
            <h3 class="modal-title">
                <span class="modal-icon">📊</span>
                比赛进度检查结果
            </h3>
        </div>
        <div class="modal-body">
            <div class="progress-info">
                <div class="progress-stat">
                    <div class="progress-stat-label">总对战数</div>
                    <div class="progress-stat-value" id="total-matches">0</div>
                </div>
                <div class="progress-stat">
                    <div class="progress-stat-label">已完成</div>
                    <div class="progress-stat-value" id="completed-matches">0</div>
                </div>
            </div>
            <div class="battle-status-breakdown">
                <h4 class="breakdown-title">战斗状态详情</h4>
                <div class="status-grid">
                    <div class="status-item running">
                        <div class="status-icon">🔄</div>
                        <div class="status-info">
                            <div class="status-label">进行中</div>
                            <div class="status-value" id="running-battles">0</div>
                        </div>
                    </div>
                    <div class="status-item pending">
                        <div class="status-icon">⏳</div>
                        <div class="status-info">
                            <div class="status-label">等待中</div>
                            <div class="status-value" id="pending-battles">0</div>
                        </div>
                    </div>
                    <div class="status-item error">
                        <div class="status-icon">❌</div>
                        <div class="status-info">
                            <div class="status-label">错误</div>
                            <div class="status-value" id="error-battles">0</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="progress-bar-container">
                <div class="progress-bar-label">
                    <span>完成进度</span>
                    <span class="progress-percentage" id="progress-percentage">0%</span>
                </div>
                <div class="progress-bar">
                    <div class="progress-fill" id="progress-fill" style="width: 0%"></div>
                </div>
            </div>
            <div id="championship-notice" class="championship-notice" style="display: none;">
                <div class="championship-notice-icon">🏆</div>
                <p class="championship-notice-text">常规赛已完成！现在可以开始冠军赛了。</p>
            </div>
        </div>
        <div class="modal-footer">
            <button class="modal-close-btn" onclick="closeProgressModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 错误提示模态框 -->
<div id="error-modal-overlay" class="modal-overlay">
    <div class="error-modal">
        <div class="error-icon">⚠️</div>
        <h3 class="error-title" id="error-title">操作失败</h3>
        <p class="error-message" id="error-message">发生了未知错误，请稍后重试。</p>
        <div class="modal-footer">
            <button class="modal-close-btn" onclick="closeErrorModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 战斗队列状态模态框 -->
<div id="queue-status-modal-overlay" class="modal-overlay">
    <div class="progress-modal">
        <div class="modal-header">
            <h3 class="modal-title">
                <span class="modal-icon" id="queue-modal-icon">⚡</span>
                战斗队列状态
            </h3>
        </div>
        <div class="modal-body">
            <div class="progress-info">
                <div class="progress-stat">
                    <div class="progress-stat-label">队列状态</div>
                    <div class="progress-stat-value" id="queue-processing-status">检查中...</div>
                </div>
                <div class="progress-stat">
                    <div class="progress-stat-label">可用插槽</div>
                    <div class="progress-stat-value" id="queue-available-slots">0</div>
                </div>
            </div>
            <div class="progress-info">
                <div class="progress-stat">
                    <div class="progress-stat-label">队列中待处理</div>
                    <div class="progress-stat-value" id="queue-manager-pending-battles">0</div>
                </div>
                <div class="progress-stat">
                    <div class="progress-stat-label">队列运行中</div>
                    <div class="progress-stat-value" id="queue-manager-running-battles">0</div>
                </div>
            </div>
            <div class="progress-bar-container">
                <div class="progress-bar-label">
                    <span>队列负载</span>
                    <span class="progress-percentage" id="queue-load-percentage">0%</span>
                </div>
                <div class="progress-bar">
                    <div class="progress-fill" id="queue-load-fill" style="width: 0%"></div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="modal-close-btn" onclick="closeQueueStatusModal()">关闭</button>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
    // 全局变量
    let selectedUsers = [];
    let userCodes = {}; // 存储每个用户选择的代码
    let availableUsers = []; // 可用用户列表

    // 用户权限信息
    const isUserStaff = {{ user.is_staff|yesno:"true,false" }};

    // 切换用户选择状态
    function toggleUserSelection(userId) {
        const index = selectedUsers.indexOf(userId);
        if (index > -1) {
            selectedUsers.splice(index, 1);
            delete userCodes[userId];
        } else {
            selectedUsers.push(userId);
        }
        renderUsersList();
        renderCodesSelection();
        updateConfirmButton();
        updateSelectAllCheckbox();
    }

    // 全选/取消全选功能
    function toggleSelectAll() {
        const selectAllCheckbox = document.getElementById('select-all-users');
        const selectAllText = document.getElementById('select-all-text');

        if (selectAllCheckbox.checked) {
            // 全选：选择所有可用用户
            selectedUsers = [...availableUsers.map(user => user.id)];
            selectAllText.textContent = '取消全选';
        } else {
            // 取消全选：清空所有选择
            selectedUsers = [];
            userCodes = {};
            selectAllText.textContent = '全选';
        }

        renderUsersList();
        renderCodesSelection();
        updateConfirmButton();
    }

    // 更新全选复选框状态
    function updateSelectAllCheckbox() {
        const selectAllCheckbox = document.getElementById('select-all-users');
        const selectAllText = document.getElementById('select-all-text');

        if (!selectAllCheckbox) return;

        const totalUsers = availableUsers.length;
        const selectedCount = selectedUsers.length;

        if (selectedCount === 0) {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
            selectAllText.textContent = '全选';
        } else if (selectedCount === totalUsers) {
            selectAllCheckbox.checked = true;
            selectAllCheckbox.indeterminate = false;
            selectAllText.textContent = '取消全选';
        } else {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = true;
            selectAllText.textContent = '全选';
        }
    }

    // 渲染用户列表
    function renderUsersList() {
        const container = document.getElementById('users-list');
        if (!availableUsers || availableUsers.length === 0) {
            container.innerHTML = '<div class="col-12 text-center text-muted"><i class="fas fa-info-circle"></i> 暂无可用用户</div>';
            return;
        }

        let html = '';
        availableUsers.forEach(user => {
            const isSelected = selectedUsers.includes(user.id);
            html += `
                <div class="col-lg-3 col-md-4 col-sm-6 mb-3">
                    <div class="card user-card ${isSelected ? 'selected' : ''}" onclick="toggleUserSelection(${user.id})">
                        <div class="card-body">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="user_${user.id}" ${isSelected ? 'checked' : ''} onchange="toggleUserSelection(${user.id})">
                                <label class="form-check-label w-100" for="user_${user.id}">
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="fas fa-user" style="margin-right: 8px; color: rgba(100, 150, 255, 0.8); font-size: 1.2rem;"></i>
                                        <h6 class="mb-0 flex-grow-1">${user.username}</h6>
                                    </div>
                                    <p class="text-muted mb-2">代码数量: ${user.codes ? user.codes.length : 0}</p>
                                    <small class="text-muted">用户ID: ${user.id}</small>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        container.innerHTML = html;
    }

    // 渲染代码选择界面
    function renderCodesSelection() {
        const container = document.getElementById('codes-selection');
        const noUsersDiv = document.getElementById('no-users-selected');

        if (selectedUsers.length === 0) {
            container.style.display = 'none';
            noUsersDiv.style.display = 'block';
            return;
        }

        container.style.display = 'block';
        noUsersDiv.style.display = 'none';

        let html = '';
        selectedUsers.forEach(userId => {
            const user = availableUsers.find(u => u.id === userId);
            if (!user) return;

            // 检查用户是否有星标代码
            const hasStarredCodes = user.codes && user.codes.some(code => code.is_starred);

            html += `
                <div class="user-code-selection">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5><i class="fas fa-user"></i> ${user.username} 的代码选择</h5>
                        ${hasStarredCodes ? `
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="select_starred_${userId}"
                                       onchange="selectAllStarredCodes(${userId})">
                                <label class="form-check-label" for="select_starred_${userId}">
                                    <i class="fas fa-star text-warning"></i> 选中所有星标代码
                                </label>
                            </div>
                        ` : ''}
                    </div>
                    <div class="row">
            `;

            // 检查用户是否有代码
            if (!user.codes || !Array.isArray(user.codes) || user.codes.length === 0) {
                html += `
                    <div class="col-12">
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i> 该用户暂无可用代码
                        </div>
                    </div>
                `;
            } else {
                user.codes.forEach(code => {
                const isSelected = userCodes[userId] === code.id;
                html += `
                    <div class="col-lg-4 col-md-6 col-sm-12 mb-3">
                        <div class="card code-card code-card-${code.language} ${code.is_starred ? 'starred-code' : ''}">
                            ${code.is_starred ? '<div class="star-indicator"><i class="fas fa-star"></i></div>' : ''}
                            <div class="card-body">
                                <div class="form-check">
                                    <input class="form-check-input code-radio-${userId}" type="radio" name="code_for_user_${userId}"
                                        id="code_${code.id}_user_${userId}" value="${code.id}"
                                        ${isSelected ? 'checked' : ''}
                                        data-starred="${code.is_starred}"
                                        onchange="selectCodeForUser(${userId}, ${code.id})">
                                    <label class="form-check-label w-100" for="code_${code.id}_user_${userId}">
                                        <div class="d-flex align-items-start mb-2">
                                            ${getLanguageIcon(code.language)}
                                            <h6 class="mb-1 flex-grow-1">${code.title}</h6>
                                        </div>
                                        <p class="text-muted mb-2">${code.description.length > 50 ? code.description.substring(0, 50) + '...' : code.description}</p>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span class="badge language-badge-${code.language}">${getLanguageDisplay(code.language)}</span>
                                            <small class="text-muted">${formatDate(code.updated_at)}</small>
                                        </div>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                });
            }

            html += `
                    </div>
                </div>
            `;
        });

        container.innerHTML = html;
    }

    // 为用户选择代码
    function selectCodeForUser(userId, codeId) {
        userCodes[userId] = codeId;
        updateConfirmButton();
    }

    // 选中用户的所有星标代码
    function selectAllStarredCodes(userId) {
        const checkbox = document.getElementById(`select_starred_${userId}`);
        const user = availableUsers.find(u => u.id === userId);

        if (!user || !user.codes) return;

        if (checkbox.checked) {
            // 找到第一个星标代码并选中
            const starredCode = user.codes.find(code => code.is_starred);
            if (starredCode) {
                const radioButton = document.getElementById(`code_${starredCode.id}_user_${userId}`);
                if (radioButton) {
                    radioButton.checked = true;
                    selectCodeForUser(userId, starredCode.id);
                }
            }
        } else {
            // 取消选择
            const radioButtons = document.querySelectorAll(`.code-radio-${userId}`);
            radioButtons.forEach(radio => {
                if (radio.dataset.starred === 'true') {
                    radio.checked = false;
                }
            });
            delete userCodes[userId];
            updateConfirmButton();
        }
    }

    // 获取语言图标
    function getLanguageIcon(language) {
        const icons = {
            'python': '<i class="fab fa-python" style="margin-right: 8px; color: rgba(53, 114, 165, 0.8); font-size: 1.2rem;"></i>',
            'javascript': '<i class="fab fa-js-square" style="margin-right: 8px; color: rgba(240, 219, 79, 0.8); font-size: 1.2rem;"></i>',
            'typescript': '<i class="fab fa-js" style="margin-right: 8px; color: rgba(255, 105, 180, 0.8); font-size: 1.2rem;"></i>',
            'lua': '<i class="fas fa-moon" style="margin-right: 8px; color: rgba(46, 139, 87, 0.8); font-size: 1.2rem;"></i>'
        };
        return icons[language] || '<i class="fas fa-code" style="margin-right: 8px; color: rgba(100, 150, 255, 0.8); font-size: 1.2rem;"></i>';
    }

    // 获取语言显示名称
    function getLanguageDisplay(language) {
        const displays = {
            'python': 'Python',
            'javascript': 'JavaScript',
            'typescript': 'TypeScript',
            'lua': 'Lua'
        };
        return displays[language] || language;
    }

    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }

    // 更新确定按钮状态
    function updateConfirmButton() {
        const confirmBtn = document.getElementById('confirm-selection-btn');
        if (!confirmBtn) return;

        // 确保selectedUsers是数组且不为空
        if (!Array.isArray(selectedUsers) || selectedUsers.length === 0) {
            confirmBtn.style.display = 'none';
            return;
        }

        const allUsersHaveCode = selectedUsers.every(userId => userCodes[userId]);

        if (allUsersHaveCode) {
            confirmBtn.style.display = 'inline-flex';
        } else {
            confirmBtn.style.display = 'none';
        }
    }

    // 显示成功消息
    function showSuccessMessage(message) {
        // 创建临时成功提示
        const successDiv = document.createElement('div');
        successDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 15px 25px;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(40, 167, 69, 0.4);
            z-index: 10001;
            font-weight: 600;
            animation: slideInRight 0.3s ease;
        `;
        successDiv.textContent = message;
        document.body.appendChild(successDiv);

        // 3秒后自动移除
        setTimeout(() => {
            successDiv.style.animation = 'slideOutRight 0.3s ease';
            setTimeout(() => {
                if (successDiv.parentNode) {
                    successDiv.parentNode.removeChild(successDiv);
                }
            }, 300);
        }, 3000);
    }

    // 确定选择
    function confirmSelection() {
        if (selectedUsers.length === 0) {
            alert('请至少选择一个用户！');
            return;
        }

        const missingCodes = selectedUsers.filter(userId => !userCodes[userId]);
        if (missingCodes.length > 0) {
            alert('请为所有选中的用户选择代码！');
            return;
        }

        const participants = selectedUsers.map(userId => ({
            user_id: userId,
            code_id: userCodes[userId]
        }));

        if (confirm(`确定要保存选择的 ${participants.length} 个参赛选手吗？`)) {
            const worldcupId = {{ worldcup.id }};
            fetch(`/battles/api/admin/worldcup/${worldcupId}/manual-select-participants/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCookie('csrftoken'),
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    participants: participants
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccessMessage('参赛选手选择保存成功！');
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                } else {
                    showErrorModal('保存参赛选手失败', data.error || '未知错误');
                }
            })
            .catch(error => {
                console.error('保存参赛选手失败:', error);
                showErrorModal('保存参赛选手失败', '网络连接错误，请检查网络后重试');
            });
        }
    }

    // 获取CSRF token的辅助函数
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // Admin管理功能JavaScript处理
    document.addEventListener('DOMContentLoaded', function() {
        // 获取CSRF token
        const csrftoken = getCookie('csrftoken');

        // 通用AJAX请求函数
        function makeAdminRequest(url, successMessage, errorMessage, successCallback) {
            fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': csrftoken,
                    'Content-Type': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 显示成功消息
                    showSuccessMessage(successMessage);

                    // 执行成功回调（如果提供）
                    if (successCallback && typeof successCallback === 'function') {
                        successCallback();
                    } else {
                        // 默认行为：刷新页面
                        setTimeout(() => {
                            location.reload();
                        }, 1500);
                    }
                } else {
                    showErrorModal(errorMessage, data.error || '未知错误');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showErrorModal(errorMessage, '网络连接错误，请检查网络后重试');
            });
        }

        // 确定参赛名单
        const confirmParticipantsBtn = document.getElementById('confirm-participants-btn');
        if (confirmParticipantsBtn) {
            confirmParticipantsBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');

                // 尝试从页面获取参赛选手数量
                let existingParticipantCount = 0;
                const participantCards = document.querySelectorAll('.participant-card');
                if (participantCards.length > 0) {
                    existingParticipantCount = participantCards.length;
                } else {
                    // 如果找不到参赛选手卡片，尝试从标题中提取数字
                    const titleElements = document.querySelectorAll('h2, .section-title, .card-title');
                    for (let element of titleElements) {
                        const text = element.textContent || element.innerText;
                        if (text.includes('参赛选手')) {
                            const match = text.match(/\((\d+)\)/);
                            if (match) {
                                existingParticipantCount = parseInt(match[1]);
                                break;
                            }
                        }
                    }
                }

                let confirmMessage = '确定要确认参赛名单吗？确认后将无法修改参赛选手。';
                let requestData = {};

                if (selectedUsers && selectedUsers.length > 0) {
                    // 如果有选中的用户，准备发送选中的用户数据
                    confirmMessage = `确定要确认选中的 ${selectedUsers.length} 个参赛选手吗？确认后将无法修改参赛选手。`;

                    // 构建参赛选手数据
                    const participants = selectedUsers.map(userId => ({
                        user_id: userId,
                        code_id: userCodes[userId]
                    }));

                    requestData = { participants: participants };
                } else if (existingParticipantCount > 0) {
                    // 如果已经有参赛选手，确认现有名单
                    confirmMessage = `确定要确认现有的 ${existingParticipantCount} 个参赛选手吗？确认后将无法修改参赛选手。`;
                } else {
                    // 如果没有参赛选手，将添加所有有代码的用户
                    confirmMessage = '没有参赛选手，将添加所有有代码的用户作为参赛选手。确定要继续吗？';
                }

                if (confirm(confirmMessage)) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/confirm-participants/`;

                    // 发送请求
                    fetch(url, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': csrftoken,
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestData)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showSuccessMessage('参赛名单确认成功！');
                            setTimeout(() => {
                                location.reload();
                            }, 1500);
                        } else {
                            showErrorModal('确认参赛名单失败', data.error || '未知错误');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showErrorModal('确认参赛名单失败', '网络连接错误，请检查网络后重试');
                    });
                }
            });
        }

        // 开始常规赛
        const startRegularSeasonBtn = document.getElementById('start-regular-season-btn');
        if (startRegularSeasonBtn) {
            startRegularSeasonBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                if (confirm('确定要开始常规赛吗？开始后将自动生成所有常规赛对战。')) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/start-regular-season/`;
                    makeAdminRequest(url, '常规赛开始成功！', '开始常规赛失败');
                }
            });
        }

        // 检查比赛进度
        const checkProgressBtn = document.getElementById('check-progress-btn');
        if (checkProgressBtn) {
            checkProgressBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                const url = `/battles/api/admin/worldcup/${worldcupId}/check-progress/`;

                fetch(url, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': csrftoken,
                        'Content-Type': 'application/json',
                    },
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showProgressModal(data);

                        // 如果常规赛已完成，显示16强分组准备按钮
                        if (data.can_start_championship) {
                            const startRound16GroupingBtn = document.getElementById('start-round16-grouping-btn');
                            if (startRound16GroupingBtn) {
                                startRound16GroupingBtn.style.display = 'inline-block';
                            }
                        }
                    } else {
                        showErrorModal('检查比赛进度失败', data.error || '未知错误');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showErrorModal('检查比赛进度失败', '网络连接错误，请检查网络后重试');
                });
            });
        }

        // 16强分组准备
        const startRound16GroupingBtn = document.getElementById('start-round16-grouping-btn');
        if (startRound16GroupingBtn) {
            startRound16GroupingBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                if (confirm('确定要进行16强分组准备吗？将根据常规赛排名生成16强淘汰赛对战分组。')) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/start-round16-grouping/`;
                    makeAdminRequest(url, '16强分组准备成功！', '16强分组准备失败');
                }
            });
        }

        // 开始冠军赛战斗
        const startChampionshipBattleBtn = document.getElementById('start-championship-battle-btn');
        if (startChampionshipBattleBtn) {
            startChampionshipBattleBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                if (confirm('确定要开始冠军赛战斗吗？这将启动冠军赛的战斗队列。')) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/start-championship/`;
                    makeAdminRequest(url, '冠军赛战斗开始成功！', '开始冠军赛战斗失败');
                }
            });
        }

        // 强制结束常规赛
        const forceEndRegularSeasonBtn = document.getElementById('force-end-regular-season-btn');
        if (forceEndRegularSeasonBtn) {
            forceEndRegularSeasonBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                if (confirm('确定要强制结束常规赛吗？这将立即结束常规赛并生成冠军赛16强名单。此操作不可撤销！')) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/force-end-regular-season/`;
                    makeAdminRequest(url, '常规赛已强制结束！', '强制结束常规赛失败');
                }
            });
        }

        // 重新运行错误战斗
        const rerunErrorBattlesBtn = document.getElementById('rerun-error-battles-btn');
        if (rerunErrorBattlesBtn) {
            rerunErrorBattlesBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                if (confirm('确定要重新运行所有错误战斗吗？这将重置错误战斗的状态并重新启动它们。')) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/rerun-error-battles/`;

                    // 显示加载状态
                    this.disabled = true;
                    this.innerHTML = '🔄 正在重新运行...';

                    fetch(url, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': csrftoken,
                            'Content-Type': 'application/json',
                        },
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            let message = data.message;
                            if (data.rerun_count > 0) {
                                message += `\n成功重新运行: ${data.rerun_count} 个战斗`;
                                if (data.failed_count > 0) {
                                    message += `\n失败: ${data.failed_count} 个战斗`;
                                }
                            }
                            alert(message);
                            // 刷新页面以更新状态
                            location.reload();
                        } else {
                            alert('重新运行错误战斗失败: ' + (data.error || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('重新运行错误战斗失败: 网络错误');
                    })
                    .finally(() => {
                        // 恢复按钮状态
                        this.disabled = false;
                        this.innerHTML = '🔧 重新运行错误战斗';
                    });
                }
            });
        }

        // 拉取错误等待进常规赛队列
        const requeueErrorPendingBattlesBtn = document.getElementById('requeue-error-pending-battles-btn');
        if (requeueErrorPendingBattlesBtn) {
            requeueErrorPendingBattlesBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                if (confirm('确定要将错误和等待状态的战斗重新加入常规赛队列吗？这将防止重复战斗ID。')) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/requeue-error-pending-battles/`;

                    // 显示加载状态
                    this.disabled = true;
                    this.innerHTML = '🔄 正在加入队列...';

                    fetch(url, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': csrftoken,
                            'Content-Type': 'application/json',
                        },
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            let message = data.message;
                            if (data.requeue_count > 0) {
                                message += `\n成功加入队列: ${data.requeue_count} 个战斗`;
                                if (data.skipped_count > 0) {
                                    message += `\n已在队列中跳过: ${data.skipped_count} 个战斗`;
                                }
                                if (data.failed_count > 0) {
                                    message += `\n失败: ${data.failed_count} 个战斗`;
                                }
                            }
                            alert(message);
                            // 刷新页面以更新状态
                            location.reload();
                        } else {
                            alert('加入队列失败: ' + (data.error || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('加入队列失败: 网络错误');
                    })
                    .finally(() => {
                        // 恢复按钮状态
                        this.disabled = false;
                        this.innerHTML = '🚀 拉取错误等待进常规赛队列';
                    });
                }
            });
        }

        // ========== 冠军赛管理功能 ==========

        // 检查冠军赛进度
        const checkChampionshipProgressBtn = document.getElementById('check-championship-progress-btn');
        if (checkChampionshipProgressBtn) {
            checkChampionshipProgressBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                const url = `/battles/api/admin/worldcup/${worldcupId}/check-championship-progress/`;

                fetch(url, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': csrftoken,
                        'Content-Type': 'application/json',
                    },
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showProgressModal(data);
                    } else {
                        showErrorModal('检查冠军赛进度失败', data.error || '未知错误');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showErrorModal('检查冠军赛进度失败', '网络连接错误，请检查网络后重试');
                });
            });
        }

        // 冠军赛队列状态
        const championshipQueueStatusBtn = document.getElementById('championship-queue-status-btn');
        if (championshipQueueStatusBtn) {
            championshipQueueStatusBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                showChampionshipQueueStatusModal(worldcupId);
            });
        }

        // 冠军赛队列控制按钮（重启/停止）
        const championshipQueueControlBtn = document.getElementById('championship-queue-control-btn');
        if (championshipQueueControlBtn) {
            championshipQueueControlBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                const action = this.getAttribute('data-action');

                if (action === 'restart') {
                    if (confirm('确定要重启冠军赛队列吗？这将重新开始处理冠军赛队列中的战斗。')) {
                        const url = `/battles/api/admin/worldcup/${worldcupId}/restart-championship-queue/`;
                        makeAdminRequest(url, '冠军赛队列已重启！', '重启冠军赛队列失败', () => {
                            fetchChampionshipQueueStatusAndUpdateButton(worldcupId);
                        });
                    }
                } else if (action === 'stop') {
                    if (confirm('确定要停止冠军赛队列吗？这将暂停新冠军赛战斗的启动，但不会影响正在进行的战斗。')) {
                        const url = `/battles/api/admin/worldcup/${worldcupId}/stop-championship-queue/`;
                        makeAdminRequest(url, '冠军赛队列已停止！', '停止冠军赛队列失败', () => {
                            fetchChampionshipQueueStatusAndUpdateButton(worldcupId);
                        });
                    }
                }
            });
        }

        // 重新运行冠军赛错误战斗
        const rerunChampionshipErrorBattlesBtn = document.getElementById('rerun-championship-error-battles-btn');
        if (rerunChampionshipErrorBattlesBtn) {
            rerunChampionshipErrorBattlesBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                if (confirm('确定要重新运行所有冠军赛错误战斗吗？这将重置错误战斗的状态并重新启动它们。')) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/rerun-championship-error-battles/`;

                    // 显示加载状态
                    this.disabled = true;
                    this.innerHTML = '🔄 正在重新运行...';

                    fetch(url, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': csrftoken,
                            'Content-Type': 'application/json',
                        },
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            let message = data.message;
                            if (data.rerun_count > 0) {
                                message += `\n成功重新运行: ${data.rerun_count} 个冠军赛战斗`;
                                if (data.failed_count > 0) {
                                    message += `\n失败: ${data.failed_count} 个冠军赛战斗`;
                                }
                            }
                            alert(message);
                            // 刷新页面以更新状态
                            location.reload();
                        } else {
                            alert('重新运行冠军赛错误战斗失败: ' + (data.error || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('重新运行冠军赛错误战斗失败: 网络错误');
                    })
                    .finally(() => {
                        // 恢复按钮状态
                        this.disabled = false;
                        this.innerHTML = '🔧 重新运行冠军赛错误战斗';
                    });
                }
            });
        }

        // 拉取错误等待进冠军赛队列
        const requeueChampionshipErrorPendingBattlesBtn = document.getElementById('requeue-championship-pending-battles-btn');
        if (requeueChampionshipErrorPendingBattlesBtn) {
            requeueChampionshipErrorPendingBattlesBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                if (confirm('确定要将错误和等待状态的冠军赛战斗重新加入队列吗？这将防止重复战斗ID。')) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/requeue-championship-error-pending-battles/`;

                    // 显示加载状态
                    this.disabled = true;
                    this.innerHTML = '🔄 正在加入队列...';

                    fetch(url, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': csrftoken,
                            'Content-Type': 'application/json',
                        },
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            let message = data.message;
                            if (data.requeue_count > 0) {
                                message += `\n成功加入队列: ${data.requeue_count} 个冠军赛战斗`;
                                if (data.skipped_count > 0) {
                                    message += `\n已在队列中跳过: ${data.skipped_count} 个冠军赛战斗`;
                                }
                                if (data.failed_count > 0) {
                                    message += `\n失败: ${data.failed_count} 个冠军赛战斗`;
                                }
                            }
                            alert(message);
                            // 刷新页面以更新状态
                            location.reload();
                        } else {
                            alert('加入队列失败: ' + (data.error || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('加入队列失败: 网络错误');
                    })
                    .finally(() => {
                        // 恢复按钮状态
                        this.disabled = false;
                        this.innerHTML = '🚀 拉取错误等待进冠军队列';
                    });
                }
            });
        }

        // 强制结束冠军赛
        const forceEndChampionshipBtn = document.getElementById('force-end-championship-btn');
        if (forceEndChampionshipBtn) {
            forceEndChampionshipBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                if (confirm('确定要强制结束冠军赛吗？这将立即结束冠军赛并确定最终排名。此操作不可撤销！')) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/force-end-championship/`;
                    makeAdminRequest(url, '冠军赛已强制结束！', '强制结束冠军赛失败');
                }
            });
        }

        // 手动推进下一阶段
        const advanceNextStageBtn = document.getElementById('advance-next-stage-btn');
        if (advanceNextStageBtn) {
            advanceNextStageBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                if (confirm('确定要手动推进到下一阶段吗？这将检查当前阶段的完成情况并创建下一阶段的比赛。')) {
                    const url = `/battles/api/admin/worldcup/${worldcupId}/advance-next-stage/`;
                    makeAdminRequest(url, '成功推进到下一阶段！', '推进下一阶段失败', () => {
                        // 成功后刷新页面以显示最新状态
                        window.location.reload();
                    });
                }
            });
        }

        // 获取队列状态并更新按钮
        function fetchQueueStatusAndUpdateButton(worldcupId) {
            // 检查用户权限，只有admin用户才能调用admin API
            if (!isUserStaff) {
                return;
            }

            const url = `/battles/api/admin/worldcup/${worldcupId}/battle-queue-status/`;

            fetch(url, {
                method: 'GET',
                headers: {
                    'X-CSRFToken': csrftoken,
                    'Content-Type': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const queueStatus = data.queue_status;
                    updateQueueControlButton(queueStatus.is_processing);
                }
            })
            .catch(error => {
                console.error('Error fetching queue status:', error);
            });
        }

        // 战斗队列状态
        const battleQueueStatusBtn = document.getElementById('battle-queue-status-btn');
        if (battleQueueStatusBtn) {
            battleQueueStatusBtn.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                showQueueStatusModal(worldcupId);
            });
        }

        // 队列控制按钮（重启/停止）
        const queueControlBtnElement = document.getElementById('queue-control-btn');
        if (queueControlBtnElement) {
            queueControlBtnElement.addEventListener('click', function() {
                const worldcupId = this.getAttribute('data-worldcup-id');
                const action = this.getAttribute('data-action');

                if (action === 'restart') {
                    if (confirm('确定要重启战斗队列吗？这将重新开始处理队列中的战斗。')) {
                        const url = `/battles/api/admin/worldcup/${worldcupId}/restart-battle-queue/`;
                        makeAdminRequest(url, '战斗队列已重启！', '重启战斗队列失败', () => {
                            // 成功后更新按钮状态
                            fetchQueueStatusAndUpdateButton(worldcupId);
                        });
                    }
                } else if (action === 'stop') {
                    if (confirm('确定要停止战斗队列吗？这将暂停新战斗的启动，但不会影响正在进行的战斗。')) {
                        const url = `/battles/api/admin/worldcup/${worldcupId}/stop-battle-queue/`;
                        makeAdminRequest(url, '战斗队列已停止！', '停止战斗队列失败', () => {
                            // 成功后更新按钮状态
                            fetchQueueStatusAndUpdateButton(worldcupId);
                        });
                    }
                }
            });
        }

        // 模态框控制函数
        window.showProgressModal = function(data) {
            // 更新数据
            document.getElementById('total-matches').textContent = data.total_matches;
            document.getElementById('completed-matches').textContent = data.finished_battles || 0;
            document.getElementById('progress-percentage').textContent = data.progress + '%';

            // 更新战斗状态详情
            document.getElementById('running-battles').textContent = data.running_battles || 0;
            document.getElementById('pending-battles').textContent = data.pending_battles || 0;
            document.getElementById('error-battles').textContent = data.error_battles || 0;

            // 动画更新进度条
            const progressFill = document.getElementById('progress-fill');
            setTimeout(() => {
                progressFill.style.width = data.progress + '%';
            }, 100);

            // 显示冠军赛通知
            const championshipNotices = document.querySelectorAll('#championship-notice');
            championshipNotices.forEach(notice => {
                if (data.can_start_championship) {
                    notice.style.display = 'block';
                } else {
                    notice.style.display = 'none';
                }
            });

            // 显示模态框
            const modal = document.getElementById('progress-modal-overlay');
            modal.classList.add('show');
        };

        window.closeProgressModal = function() {
            const modal = document.getElementById('progress-modal-overlay');
            modal.classList.remove('show');
        };

        window.showErrorModal = function(title, message) {
            document.getElementById('error-title').textContent = title;
            document.getElementById('error-message').textContent = message;

            const modal = document.getElementById('error-modal-overlay');
            modal.classList.add('show');
        };

        window.closeErrorModal = function() {
            const modal = document.getElementById('error-modal-overlay');
            modal.classList.remove('show');
        };

        // 点击遮罩层关闭模态框
        document.getElementById('progress-modal-overlay').addEventListener('click', function(e) {
            if (e.target === this) {
                closeProgressModal();
            }
        });

        document.getElementById('error-modal-overlay').addEventListener('click', function(e) {
            if (e.target === this) {
                closeErrorModal();
            }
        });

        // 初始化队列控制按钮状态
        const queueControlBtnInit = document.getElementById('queue-control-btn');
        if (queueControlBtnInit) {
            const worldcupId = queueControlBtnInit.getAttribute('data-worldcup-id');
            if (worldcupId) {
                fetchQueueStatusAndUpdateButton(worldcupId);
            }
        }

        // 初始化战斗队列状态按钮状态
        const battleQueueStatusBtnInit = document.getElementById('battle-queue-status-btn');
        if (battleQueueStatusBtnInit) {
            const worldcupId = battleQueueStatusBtnInit.getAttribute('data-worldcup-id');
            if (worldcupId) {
                fetchQueueStatusForButtonUpdate(worldcupId);
            }
        }

        // 初始化冠军赛队列控制按钮状态
        const championshipQueueControlBtnInit = document.getElementById('championship-queue-control-btn');
        if (championshipQueueControlBtnInit) {
            const worldcupId = championshipQueueControlBtnInit.getAttribute('data-worldcup-id');
            if (worldcupId) {
                fetchChampionshipQueueStatusAndUpdateButton(worldcupId);
            }
        }

        // 初始化冠军赛队列状态按钮状态
        const championshipQueueStatusBtnInit = document.getElementById('championship-queue-status-btn');
        if (championshipQueueStatusBtnInit) {
            const worldcupId = championshipQueueStatusBtnInit.getAttribute('data-worldcup-id');
            if (worldcupId) {
                fetchChampionshipQueueStatusForButtonUpdate(worldcupId);
            }
        }

    });

    // 加载可用用户列表
    function loadAvailableUsers() {
        const worldcupId = {{ worldcup.id }};
        fetch(`/battles/api/admin/worldcup/${worldcupId}/available-users/`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    availableUsers = data.users;
                    renderUsersList();
                    updateSelectAllCheckbox();
                } else {
                    document.getElementById('users-list').innerHTML =
                        '<div class="col-12 text-center text-danger"><i class="fas fa-exclamation-triangle"></i> 加载用户列表失败: ' + (data.error || '未知错误') + '</div>';
                }
            })
            .catch(error => {
                console.error('加载用户列表失败:', error);
                document.getElementById('users-list').innerHTML =
                    '<div class="col-12 text-center text-danger"><i class="fas fa-exclamation-triangle"></i> 网络错误，请检查网络连接</div>';
            });
    }

    // 绑定确定按钮事件（仅在按钮存在时）
    const confirmBtn = document.getElementById('confirm-selection-btn');
    if (confirmBtn) {
        confirmBtn.addEventListener('click', confirmSelection);
    }

    // 页面加载时初始化
    if (document.getElementById('users-list')) {
        loadAvailableUsers();
    }

    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeProgressModal();
            closeErrorModal();
            closeQueueStatusModal();
        }
    });

    // 更新队列控制按钮状态
    function updateQueueControlButton(isProcessing) {
        const queueControlBtn = document.getElementById('queue-control-btn');
        const queueControlIcon = document.getElementById('queue-control-icon');
        const queueControlText = document.getElementById('queue-control-text');

        if (queueControlBtn) {
            queueControlBtn.style.display = 'inline-flex';

            // 移除所有可能的样式类
            queueControlBtn.classList.remove('btn-warning', 'btn-danger', 'btn-success');

            if (isProcessing) {
                // 队列运行中 - 显示停止按钮
                queueControlIcon.textContent = '⏹️';
                queueControlText.textContent = '停止战斗队列';
                queueControlBtn.classList.add('btn-danger');
                queueControlBtn.setAttribute('data-action', 'stop');
            } else {
                // 队列已停止 - 显示重启按钮
                queueControlIcon.textContent = '🔄';
                queueControlText.textContent = '重启战斗队列';
                queueControlBtn.classList.add('btn-success');
                queueControlBtn.setAttribute('data-action', 'restart');
            }
        }
    }

    // 队列状态模态框相关函数
    function showQueueStatusModal(worldcupId) {
        const modal = document.getElementById('queue-status-modal-overlay');
        if (modal) {
            modal.classList.add('show');
            fetchQueueStatusData(worldcupId);
        }
    }

    function closeQueueStatusModal() {
        const modal = document.getElementById('queue-status-modal-overlay');
        if (modal) {
            modal.classList.remove('show');
        }
    }

    function fetchQueueStatusData(worldcupId) {
        // 检查用户权限，只有admin用户才能调用admin API
        if (!isUserStaff) {
            return;
        }

        const url = `/battles/api/admin/worldcup/${worldcupId}/battle-queue-status/`;

        fetch(url, {
            method: 'GET',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateQueueStatusModal(data.queue_status, data.battle_stats);
                updateBattleQueueStatusButton(data.queue_status);
                updateQueueControlButton(data.queue_status.is_processing);
            } else {
                showErrorModal('获取队列状态失败', data.error || '未知错误');
                closeQueueStatusModal();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showErrorModal('网络错误', '无法获取队列状态，请检查网络连接');
            closeQueueStatusModal();
        });
    }

    function updateQueueStatusModal(queueStatus, battleStats) {
        // 更新队列状态
        const processingStatus = document.getElementById('queue-processing-status');
        if (processingStatus) {
            processingStatus.textContent = queueStatus.is_processing ? '运行中' : '已停止';
            processingStatus.style.color = queueStatus.is_processing ? '#28a745' : '#dc3545';
        }

        // 更新可用插槽
        const availableSlots = document.getElementById('queue-available-slots');
        if (availableSlots) {
            availableSlots.textContent = queueStatus.available_slots || 0;
        }

        // 更新队列管理器中的待处理战斗
        const queueManagerPendingBattles = document.getElementById('queue-manager-pending-battles');
        if (queueManagerPendingBattles) {
            queueManagerPendingBattles.textContent = queueStatus.pending_battles || 0;
        }

        // 更新数据库中的pending状态战斗
        const pendingBattles = document.getElementById('queue-pending-battles');
        if (pendingBattles) {
            pendingBattles.textContent = battleStats.pending || 0;
        }

        // 更新数据库中的运行中战斗
        const runningBattles = document.getElementById('queue-running-battles');
        if (runningBattles) {
            runningBattles.textContent = battleStats.running || 0;
        }

        // 更新队列管理器中的运行中战斗
        const queueManagerRunningBattles = document.getElementById('queue-manager-running-battles');
        if (queueManagerRunningBattles) {
            queueManagerRunningBattles.textContent = queueStatus.running_battles || 0;
        }

        // 更新已完成战斗
        const finishedBattles = document.getElementById('queue-finished-battles');
        if (finishedBattles) {
            finishedBattles.textContent = battleStats.finished || 0;
        }

        // 更新错误战斗
        const errorBattles = document.getElementById('queue-error-battles');
        if (errorBattles) {
            errorBattles.textContent = battleStats.error || 0;
        }

        // 更新队列负载
        const maxConcurrent = queueStatus.max_concurrent || 50;
        const currentLoad = queueStatus.running_battles || 0;
        const loadPercentage = Math.round((currentLoad / maxConcurrent) * 100);

        const loadPercentageElement = document.getElementById('queue-load-percentage');
        const loadFillElement = document.getElementById('queue-load-fill');

        if (loadPercentageElement) {
            loadPercentageElement.textContent = `${loadPercentage}%`;
        }

        if (loadFillElement) {
            loadFillElement.style.width = `${loadPercentage}%`;

            // 根据负载设置颜色
            if (loadPercentage < 50) {
                loadFillElement.style.background = 'linear-gradient(90deg, #28a745, #20c997)';
            } else if (loadPercentage < 80) {
                loadFillElement.style.background = 'linear-gradient(90deg, #ffc107, #fd7e14)';
            } else {
                loadFillElement.style.background = 'linear-gradient(90deg, #dc3545, #6f42c1)';
            }
        }
    }

    function updateBattleQueueStatusButton(queueStatus) {
        const btn = document.getElementById('battle-queue-status-btn');
        const icon = document.getElementById('queue-status-icon');

        if (!btn) {
            return;
        }

        // 移除所有状态类
        btn.classList.remove('queue-idle', 'queue-busy', 'queue-overloaded', 'queue-error');

        const maxConcurrent = queueStatus.max_concurrent || 50;
        const currentLoad = queueStatus.running_battles || 0;
        const loadPercentage = (currentLoad / maxConcurrent) * 100;

        if (!queueStatus.is_processing) {
            // 队列未运行
            btn.classList.add('queue-error');
            if (icon) icon.textContent = '⏸️';
        } else if (loadPercentage < 50) {
            // 负载较低
            btn.classList.add('queue-idle');
            if (icon) icon.textContent = '✅';
        } else if (loadPercentage < 80) {
            // 负载中等
            btn.classList.add('queue-busy');
            if (icon) icon.textContent = '⚡';
        } else {
            // 负载过高
            btn.classList.add('queue-overloaded');
            if (icon) icon.textContent = '🔥';
        }
    }

    // 点击遮罩层关闭队列状态模态框
    document.getElementById('queue-status-modal-overlay')?.addEventListener('click', function(e) {
        if (e.target === this) {
            closeQueueStatusModal();
        }
    });

    // 仅用于更新按钮状态的函数（不显示模态框）
    function fetchQueueStatusForButtonUpdate(worldcupId) {
        // 检查用户权限，只有admin用户才能调用admin API
        if (!isUserStaff) {
            return;
        }

        const url = `/battles/api/admin/worldcup/${worldcupId}/battle-queue-status/`;

        fetch(url, {
            method: 'GET',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateBattleQueueStatusButton(data.queue_status);
                
                // 集成自动检测逻辑：检查是否需要自动重新加入战斗
                const queueStatus = data.queue_status;
                const battleStats = data.battle_stats;

                // 检查是否满足自动重新加入的条件：
                // 1. 队列正在处理中
                // 2. 队列中待处理和运行中的战斗数量都为0
                // 3. 数据库中有错误或等待中的战斗
                if (queueStatus.is_processing && 
                    queueStatus.pending_battles === 0 && 
                    queueStatus.running_battles === 0 &&
                    (battleStats.error > 0 || battleStats.pending > 0)) {
                    
                    console.log('检测到队列空闲且有错误/等待中战斗，自动重新加入战斗到队列...');
                    console.log('队列状态:', queueStatus);
                    console.log('战斗统计:', battleStats);
                    autoRequeueRegularBattles(worldcupId);
                }
            } else {
                console.error('API返回错误:', data.error);
                // 如果API返回错误，设置按钮为错误状态
                const btn = document.getElementById('battle-queue-status-btn');
                const icon = document.getElementById('queue-status-icon');
                if (btn) {
                    btn.classList.remove('queue-idle', 'queue-busy', 'queue-overloaded', 'queue-error');
                    btn.classList.add('queue-error');
                    if (icon) icon.textContent = '❌';
                }
            }
        })
        .catch(error => {
            console.error('Error fetching queue status for button update:', error);
        });
    }

    // ========== 冠军赛队列状态相关函数 ==========

    // 获取冠军赛队列状态并更新按钮
    function fetchChampionshipQueueStatusAndUpdateButton(worldcupId) {
        const url = `/battles/api/admin/worldcup/${worldcupId}/championship-queue-status/`;

        fetch(url, {
            method: 'GET',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const queueStatus = data.queue_status;
                updateChampionshipQueueControlButton(queueStatus.is_processing);
            }
        })
        .catch(error => {
            console.error('Error fetching championship queue status:', error);
        });
    }

    // 更新冠军赛队列控制按钮状态
    function updateChampionshipQueueControlButton(isProcessing) {
        const queueControlBtn = document.getElementById('championship-queue-control-btn');
        const queueControlIcon = document.getElementById('championship-queue-control-icon');
        const queueControlText = document.getElementById('championship-queue-control-text');

        if (queueControlBtn) {
            queueControlBtn.style.display = 'inline-flex';

            // 移除所有可能的样式类
            queueControlBtn.classList.remove('btn-warning', 'btn-danger', 'btn-success');

            if (isProcessing) {
                // 队列运行中 - 显示停止按钮
                queueControlIcon.textContent = '⏹️';
                queueControlText.textContent = '停止冠军赛队列';
                queueControlBtn.classList.add('btn-danger');
                queueControlBtn.setAttribute('data-action', 'stop');
            } else {
                // 队列已停止 - 显示重启按钮
                queueControlIcon.textContent = '🔄';
                queueControlText.textContent = '重启冠军赛队列';
                queueControlBtn.classList.add('btn-success');
                queueControlBtn.setAttribute('data-action', 'restart');
            }
        }
    }

    // 显示冠军赛队列状态模态框
    function showChampionshipQueueStatusModal(worldcupId) {
        const url = `/battles/api/admin/worldcup/${worldcupId}/championship-queue-status/`;

        fetch(url, {
            method: 'GET',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新模态框内容（复用现有的队列状态模态框，但修改标题）
                const modalTitle = document.querySelector('#queue-status-modal-overlay .modal-title');
                if (modalTitle) {
                    modalTitle.innerHTML = '<span class="modal-icon">🏆</span>冠军赛队列状态';
                }

                // 更新队列状态数据
                updateQueueStatusModal(data.queue_status, data.battle_stats);

                // 显示模态框
                const modal = document.getElementById('queue-status-modal-overlay');
                modal.classList.add('show');
            } else {
                showErrorModal('获取冠军赛队列状态失败', data.error || '未知错误');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showErrorModal('获取冠军赛队列状态失败', '网络连接错误，请检查网络后重试');
        });
    }

    // 仅用于更新冠军赛队列状态按钮的函数（不显示模态框）
    function fetchChampionshipQueueStatusForButtonUpdate(worldcupId) {
        const url = `/battles/api/admin/worldcup/${worldcupId}/championship-queue-status/`;

        fetch(url, {
            method: 'GET',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateChampionshipBattleQueueStatusButton(data.queue_status);
            } else {
                console.error('冠军赛API返回错误:', data.error);
                // 如果API返回错误，设置按钮为错误状态
                const btn = document.getElementById('championship-queue-status-btn');
                const icon = document.getElementById('championship-queue-status-icon');
                if (btn) {
                    btn.classList.remove('queue-idle', 'queue-busy', 'queue-overloaded', 'queue-error');
                    btn.classList.add('queue-error');
                    if (icon) icon.textContent = '❌';
                }
            }
        })
        .catch(error => {
            console.error('Error fetching championship queue status for button update:', error);
        });
    }

    // 更新冠军赛队列状态按钮
    function updateChampionshipBattleQueueStatusButton(queueStatus) {
        const btn = document.getElementById('championship-queue-status-btn');
        const icon = document.getElementById('championship-queue-status-icon');

        if (!btn) {
            console.error('未找到冠军赛队列状态按钮');
            return;
        }

        // 移除所有状态类
        btn.classList.remove('queue-idle', 'queue-busy', 'queue-overloaded', 'queue-error');

        if (queueStatus.total_battles === 0) {
            // 空闲状态
            btn.classList.add('queue-idle');
            if (icon) icon.textContent = '💤';
        } else if (queueStatus.running_battles >= 10) {
            // 负载过高
            btn.classList.add('queue-overloaded');
            if (icon) icon.textContent = '🔥';
        } else if (queueStatus.running_battles > 0) {
            // 繁忙状态
            btn.classList.add('queue-busy');
            if (icon) icon.textContent = '⚡';
        } else {
            // 空闲状态
            btn.classList.add('queue-idle');
            if (icon) icon.textContent = '💤';
        }
    }

    // 页面加载时刷新最新数据
    document.addEventListener('DOMContentLoaded', function() {
        // 页面加载时刷新最新数据
        refreshData();
    });

    // ========== 手动刷新功能 ==========

    // 执行数据刷新的具体逻辑
    function performDataRefresh(worldcupId, worldcupStatus) {
        // 根据状态选择合适的API接口
        let apiUrl;
        if (worldcupStatus === 'regular_season') {
            apiUrl = `/battles/api/worldcup/${worldcupId}/regular-season-data/`;
        } else if (worldcupStatus === 'championship') {
            apiUrl = `/battles/api/worldcup/${worldcupId}/championship-data/`;
        } else if (worldcupStatus === 'regular_finished' || worldcupStatus === 'championship_ready') {
            // 对于这些状态，我们仍然获取常规赛数据来显示最终结果
            apiUrl = `/battles/api/worldcup/${worldcupId}/regular-season-data/`;
        } else {
            return;
        }

        fetch(apiUrl)
            .then(response => {
                return response.json();
            })
            .then(data => {

                if (data.status === 'success' && data.data) {
                    // 处理常规赛数据
                    if (worldcupStatus === 'regular_season') {
                        if (data.data.participants) {
                            updateParticipantsData(data.data.participants);
                        }

                        // 直接使用API返回的进度数据
                        if (data.data.progress) {
                            updateProgressData(data.data.progress);
                            updateProgressBar(data.data.progress);
                        }
                    }
                    // 处理冠军赛数据
                    else if (worldcupStatus === 'championship') {

                        // 处理参赛选手数据
                        if (data.data.participants) {
                            updateParticipantsData(data.data.participants);
                        }

                        // 处理冠军赛比赛数据
                        if (data.data.championship_matches) {
                            const allMatches = [];
                            // 合并所有阶段的比赛
                            Object.values(data.data.championship_matches).forEach(stageMatches => {
                                if (Array.isArray(stageMatches)) {
                                    allMatches.push(...stageMatches);
                                }
                            });

                            // 转换为recent_battles格式
                            const recentBattles = allMatches.map(match => ({
                                player1: match.player1,
                                player2: match.player2,
                                status: match.battle_status || match.status,
                                created_at: match.created_at
                            }));

                            // 构造进度数据
                            const progressData = {
                                total_matches: allMatches.length,
                                finished_battles: allMatches.filter(m => (m.battle_status || m.status) === 'finished').length,
                                running_battles: allMatches.filter(m => (m.battle_status || m.status) === 'running').length,
                                pending_battles: allMatches.filter(m => (m.battle_status || m.status) === 'pending').length,
                                error_battles: allMatches.filter(m => (m.battle_status || m.status) === 'error').length,
                                progress: allMatches.length > 0 ?
                                    Math.round((allMatches.filter(m => (m.battle_status || m.status) === 'finished').length / allMatches.length) * 100) : 0
                            };
                            updateProgressData(progressData);
                            updateProgressBar(progressData);
                        }
                    }
                } else {
                    console.error('刷新数据失败:', data.error || '未知错误');
                }
            })
            .catch(error => {
                console.error('刷新请求失败:', error);
            });

        // 刷新战斗队列状态按钮
        refreshBattleQueueStatus(worldcupId, worldcupStatus);
    }

    // 刷新战斗队列状态按钮
    function refreshBattleQueueStatus(worldcupId, worldcupStatus) {
        // 根据世界杯状态刷新对应的队列状态按钮
        if (worldcupStatus === 'regular_season') {
            // 刷新常规赛队列状态按钮（已集成自动检测逻辑）
            fetchQueueStatusForButtonUpdate(worldcupId);
        } else if (worldcupStatus === 'championship') {
            // 刷新冠军赛队列状态按钮
            fetchChampionshipQueueStatusForButtonUpdate(worldcupId);
        }
    }

    // 检查并自动重新加入常规赛战斗到队列
    function checkAndAutoRequeueRegularBattles(worldcupId) {
        // 只有管理员才能执行自动重新加入操作
        if (!{{ user.is_staff|yesno:"true,false" }}) {
            return;
        }

        const url = `/battles/api/admin/worldcup/${worldcupId}/battle-queue-status/`;

        fetch(url, {
            method: 'GET',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const queueStatus = data.queue_status;
                const battleStats = data.battle_stats;

                // 检查是否满足自动重新加入的条件：
                // 1. 队列正在处理中
                // 2. 队列中待处理和运行中的战斗数量都为0
                // 3. 数据库中有错误或等待中的战斗
                if (queueStatus.is_processing && 
                    queueStatus.pending_battles === 0 && 
                    queueStatus.running_battles === 0 &&
                    (battleStats.error > 0 || battleStats.pending > 0)) {
                    
                    console.log('检测到队列空闲且有错误/等待中战斗，自动重新加入战斗到队列...');
                    autoRequeueRegularBattles(worldcupId);
                }
            }
        })
        .catch(error => {
            console.error('检查队列状态失败:', error);
        });
    }

    // 自动重新加入常规赛战斗到队列
    function autoRequeueRegularBattles(worldcupId) {
        const url = `/battles/api/admin/worldcup/${worldcupId}/auto-requeue-battles/`;

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log(`自动重新加入成功: ${data.message}`);
                console.log(`重新加入的战斗数量: ${data.requeued_count}`);
                
                // 显示成功提示（可选，避免过于频繁的提示）
                if (data.requeued_count > 0) {
                    showMessage(`自动重新加入了 ${data.requeued_count} 场战斗到队列`, 'success');
                    
                    // 刷新队列状态显示
                    setTimeout(() => {
                        fetchQueueStatusForButtonUpdate(worldcupId);
                    }, 1000);
                }
            } else {
                // 只在非预期的错误时显示错误信息
                if (!data.error.includes('队列未启动') && 
                    !data.error.includes('队列中仍有战斗在处理中') && 
                    !data.error.includes('数据库中没有错误或等待中的战斗')) {
                    console.error('自动重新加入战斗失败:', data.error);
                }
            }
        })
        .catch(error => {
            console.error('自动重新加入战斗请求失败:', error);
        });
    }

    // 手动刷新数据的函数
    function refreshData() {
        const worldcupId = {{ worldcup.id }};
        const worldcupStatus = '{{ worldcup.status }}';

        // 首先检查世界杯状态是否发生变化
        fetch(`/battles/api/worldcup/${worldcupId}/status/`)
            .then(response => response.json())
            .then(statusData => {
                if (statusData.status === 'success' && statusData.data && statusData.data.status !== worldcupStatus) {
                    // 状态发生变化，刷新页面
                    console.log(`世界杯状态从 ${worldcupStatus} 变更为 ${statusData.data.status}，刷新页面...`);
                    window.location.reload();
                    return;
                }

                // 状态未变化，继续正常的数据刷新
                performDataRefresh(worldcupId, worldcupStatus);
            })
            .catch(error => {
                console.error('检查状态失败，继续正常刷新:', error);
                performDataRefresh(worldcupId, worldcupStatus);
            });
    }

    // 更新参赛选手数据
    function updateParticipantsData(participants) {
        if (!participants || !Array.isArray(participants)) return;

        // 直接查找participants-grid容器
        const participantsGrid = document.querySelector('.participants-grid');
        if (!participantsGrid) {
            console.error('未找到participants-grid容器');
            return;
        }

        // 更新参赛选手列表
        let participantsHtml = '';
        participants.forEach(participant => {
            const championshipRank = participant.championship_rank ?
                `<div class="championship-rank">冠军赛排名: ${participant.championship_rank}</div>` : '';

            // 兼容不同的字段名格式
            const username = participant.username || participant.user__username || participant.user?.username || '未知用户';
            const score = participant.score || participant.total_score || 0;
            const wins = participant.wins || 0;
            const losses = participant.losses || 0;
            const winRate = participant.win_rate || 0;

            // 只在准备阶段且用户是管理员时显示删除按钮
            const deleteButton = ('{{ worldcup.status }}' === 'preparing' && {{ user.is_staff|yesno:"true,false" }}) ?
                `<button class="participant-delete-btn"
                         data-participant-id="${participant.id}"
                         data-participant-name="${username}"
                         title="删除参赛选手">×</button>` : '';

            participantsHtml += `
                <div class="participant-card">
                    ${deleteButton}
                    <div class="participant-info">
                        <div class="participant-name">${username}</div>
                        <div class="participant-code">代码: ${participant.code_title || '未知代码'}</div>
                        <div class="participant-score">积分: ${score}</div>
                        <div class="participant-stats">胜: ${wins} 负: ${losses} 胜率: ${winRate}%</div>
                        ${championshipRank}
                    </div>
                </div>
            `;
        });

        // 直接更新participants-grid的内容
        participantsGrid.innerHTML = participantsHtml;

        // 为新添加的删除按钮绑定事件监听器
        participantsGrid.querySelectorAll('.participant-delete-btn').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();

                const participantId = this.getAttribute('data-participant-id');
                const participantName = this.getAttribute('data-participant-name');

                removeParticipant(participantId, participantName);
            });
        });

        // 更新参赛选手数量
        const participantCountElement = document.querySelector('.participant-count, h2');
        if (participantCountElement && participantCountElement.textContent.includes('👲 参赛选手')) {
            participantCountElement.textContent = `👲 参赛选手 (${participants.length})`;
        }
    }

    // 更新比赛进度数据
    function updateProgressData(progress) {
        if (!progress) return;

        // 更新各种进度统计
        const elements = {
            'total-matches': progress.total_matches,
            'completed-matches': progress.finished_battles,
            'running-battles': progress.running_battles,
            'pending-battles': progress.pending_battles,
            'error-battles': progress.error_battles
        };

        Object.entries(elements).forEach(([id, value]) => {
            // 使用querySelectorAll来更新所有具有相同ID的元素
            const elementsWithId = document.querySelectorAll(`#${id}`);
            elementsWithId.forEach(element => {
                if (element && value !== undefined) {
                    element.textContent = value;
                }
            });
        });

        // 更新进度百分比
        const progressPercentageElements = document.querySelectorAll('#progress-percentage');
        progressPercentageElements.forEach(element => {
            if (element && progress.progress !== undefined) {
                element.textContent = progress.progress + '%';
            }
        });

        // 更新进度条填充
        const progressFillElements = document.querySelectorAll('#progress-fill');
        progressFillElements.forEach(element => {
            if (element && progress.progress !== undefined) {
                element.style.width = progress.progress + '%';
            }
        });
    }


    // 更新进度条
    function updateProgressBar(progress) {
        if (!progress || progress.progress === undefined) return;

        // 查找或创建进度条容器
        let progressBarContainer = document.querySelector('.auto-refresh-progress-bar');
        if (!progressBarContainer) {
            // 创建进度条容器
            progressBarContainer = document.createElement('div');
            progressBarContainer.className = 'auto-refresh-progress-bar';
            progressBarContainer.innerHTML = `
                <div class="progress-bar-header">
                    <h4>比赛进度</h4>
                    <span class="progress-text">${progress.progress}%</span>
                </div>
                <div class="progress-bar-wrapper">
                    <div class="progress-bar-fill" style="width: ${progress.progress}%"></div>
                </div>
                <div class="progress-details">
                    <span>已完成: ${progress.finished_battles || 0}/${progress.total_matches || 0}</span>
                    <span>进行中: ${progress.running_battles || 0}</span>
                    <span>等待中: ${progress.pending_battles || 0}</span>
                </div>
            `;

            // 添加样式
            const style = document.createElement('style');
            style.textContent = `
                .auto-refresh-progress-bar {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    border-radius: 15px;
                    padding: 20px;
                    margin: 20px 0;
                    color: white;
                    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
                }
                .progress-bar-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 15px;
                }
                .progress-bar-header h4 {
                    margin: 0;
                    font-weight: 600;
                }
                .progress-text {
                    font-size: 1.2rem;
                    font-weight: bold;
                }
                .progress-bar-wrapper {
                    background: rgba(255, 255, 255, 0.2);
                    border-radius: 10px;
                    height: 12px;
                    overflow: hidden;
                    margin-bottom: 15px;
                }
                .progress-bar-fill {
                    background: linear-gradient(90deg, #28a745, #20c997);
                    height: 100%;
                    border-radius: 10px;
                    transition: width 0.5s ease;
                    box-shadow: 0 2px 10px rgba(40, 167, 69, 0.4);
                }
                .progress-details {
                    display: flex;
                    justify-content: space-between;
                    font-size: 0.9rem;
                    opacity: 0.9;
                }
                .progress-details span {
                    background: rgba(255, 255, 255, 0.1);
                    padding: 5px 10px;
                    border-radius: 5px;
                }
            `;
            document.head.appendChild(style);

            // 将进度条插入到合适的位置
            const mainContent = document.querySelector('.container-fluid, .main-content, .card-body');
            if (mainContent) {
                mainContent.insertBefore(progressBarContainer, mainContent.firstChild);
            }
        } else {
            // 更新现有进度条
            const progressText = progressBarContainer.querySelector('.progress-text');
            const progressFill = progressBarContainer.querySelector('.progress-bar-fill');
            const progressDetails = progressBarContainer.querySelector('.progress-details');

            if (progressText) {
                progressText.textContent = progress.progress + '%';
            }
            if (progressFill) {
                progressFill.style.width = progress.progress + '%';
            }
            if (progressDetails) {
                progressDetails.innerHTML = `
                    <span>已完成: ${progress.finished_battles || 0}/${progress.total_matches || 0}</span>
                    <span>进行中: ${progress.running_battles || 0}</span>
                    <span>等待中: ${progress.pending_battles || 0}</span>
                `;
            }
        }
    }







    // 删除参赛选手功能
    function removeParticipant(participantId, participantName) {
        if (!confirm(`确定要删除参赛选手 "${participantName}" 吗？此操作不可撤销。`)) {
            return;
        }

        const worldcupId = {{ worldcup.id }};

        fetch(`/battles/api/admin/worldcup/${worldcupId}/remove-participant/${participantId}/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 显示成功消息
                showMessage(data.message, 'success');

                // 刷新页面数据
                setTimeout(() => {
                    location.reload();
                }, 1000);
            } else {
                showMessage(data.error || '删除失败', 'error');
            }
        })
        .catch(error => {
            console.error('删除参赛选手失败:', error);
            showMessage('删除失败，请重试', 'error');
        });
    }

    // 显示消息提示
    function showMessage(message, type = 'info') {
        // 移除现有的消息
        const existingMessage = document.querySelector('.message-toast');
        if (existingMessage) {
            existingMessage.remove();
        }

        const toast = document.createElement('div');
        toast.className = `message-toast message-${type}`;
        toast.textContent = message;

        const styles = {
            position: 'fixed',
            top: '20px',
            right: '20px',
            zIndex: '10001',
            padding: '12px 20px',
            borderRadius: '8px',
            color: 'white',
            fontSize: '14px',
            fontWeight: '500',
            maxWidth: '300px',
            wordWrap: 'break-word',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.3)',
            transition: 'all 0.3s ease'
        };

        Object.assign(toast.style, styles);

        if (type === 'success') {
            toast.style.background = 'linear-gradient(135deg, #28a745, #20c997)';
        } else if (type === 'error') {
            toast.style.background = 'linear-gradient(135deg, #dc3545, #c82333)';
        } else {
            toast.style.background = 'linear-gradient(135deg, #17a2b8, #138496)';
        }

        document.body.appendChild(toast);

        // 3秒后自动移除
        setTimeout(() => {
            if (toast.parentNode) {
                toast.style.opacity = '0';
                toast.style.transform = 'translateX(100%)';
                setTimeout(() => {
                    if (toast.parentNode) {
                        toast.remove();
                    }
                }, 300);
            }
        }, 3000);
    }

    // 获取CSRF Token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 为删除按钮添加事件监听器
    document.addEventListener('DOMContentLoaded', function() {
        // 为静态渲染的删除按钮添加事件监听器
        document.querySelectorAll('.participant-delete-btn').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();

                const participantId = this.getAttribute('data-participant-id');
                const participantName = this.getAttribute('data-participant-name');

                removeParticipant(participantId, participantName);
            });
        });
    });

</script>
{% endblock %}